JQuery Client-side Validation for Email Address

Introduction

In the previous article demonstrated how to perform a jquery client-side validation for html input text box on html forms. (See “JQuery Client-side Validation for Text input”). Let us take you through how to perform a jquery client-side validation for an email address on html forms. There is an immense power behind the Jquery library, when it comes to client side validation for web forms, it is all about Jquery client side validations. Below code snippet shows a simple HTML form code with email address.

Basic html form with a email text box

<form id="form2" action="" method="post">
    <!--step three-->
    <div>
        E-mail
        <input id="txtemail" type="text" />
        <span id="emailInfo">*</span><br />
        <input id="Submit2" type="submit" value="submit" />
    </div>
</form> 

This code snippet creates a simple html Form with a textbox, a label and a submit button on it. Once user click on the submit button, it will trigger html form submit action, The form action will send all the values in the input controls to sever. Before we send the html form input values may need to perform a jquery client side validation for inputs. In this case it is required to validate an email address. In the code above there is a textbox and a span to show client side error messages.

Above html code will produce a form in the browser as follows.

Form Register
Form Register

Jquery client side reference settings

Now the html form is ready to use for jquery client side validation. In order to use Jquery library, you have to download JQuery at (www.jquery.org) and set the JQuery library reference in the html page header. Once it is set can continue using JQuery client side validation. Below code shows how to set the JQuery reference;

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

As a best practice, In HTML/CSS coding, you may need to place all your javascript code in a separate files and put them in a separate folder. You can place all your custom javascript code in a file called valitioninput.js. This file must contain all the custom client side validation codes. Once all in place you can set the reference as follows;

<script type="text/javascript" src="js/validationinput.js"></script>

Building the jquery client-side email address validation code

Fist things first. You need place the document ready() event handler before you start coding any JQuery client side validation code. It has to be positioned as shown below.

$(document).ready(function() {

//All your code will wirte inside here.

});

Above piece of code will make sure once page loaded into browser whatever the code in it will start to execute.

Read required email Address inputs

Using JQuery selectors you can perform useful tasks such as read, set values or trigger events of HTML controls. Here we are using pseudo ID to select input email address for validation purpose. Then check for correctness of the values at client side. In this scenario only one textbox is going to be client-side validated. So reading of textbox value and its span tag which display the error message have to be coded.

var email = $("#txtemail"); //textbox u are going to validate

var emailInfo = $("#emailInfo"); //to display error message

These are the first two lines of code which are inside the Document Ready Event. These two variables act globally for all other functions within the ready event.

Events need to be handled for jquery client side validations

Consider the events required to client side validate the email address textbox . You are aware that the submit event of the Form is supposed to handle in all kinds of client side validation actions before values is being post to the server. For navigation through text input fields users may use either TAB or arrow keys. In such a situation the system should validate the input at the client side. The input control has to be handled onBlur event for TAB key actions. If the user chooses the mouse instead of the TAB, onKeyDown event has to be handled.

Submit event

The code below shows how to handle client-side validation for form submit event, with a trigger of submit button action inside the form.

$('#form2').submit(function() {

// validation begin before submit

});

Here, the pseudo ID has been used to select the email address value from HTML form. Once it is chosen we can use the “submit” function. Submit client side event in JQuery is called onSubmit event of the html Form control. This event will be activate when the user clicks on submit button. Once it is triggered, client side validations for input text box has to be performed. As we should carry out the same client side validation also for the other two events, the best solution will be create a separate function to perform client side validation for email address textbox. We can simply locate the jquery client side validation of the textbox into one central location, which helps trouble-free maintenance of code.

Your submit event handler code will be as follows;

//first validation on form submit

form.submit(function() {

// validation begin before submit

if (validateEmail()) {

return true;

} else {

return false;

}

});

If the “validateEmail” returns false, it will be either submitted or will display client side error messages.

Blur Event

Same client side validate function can be called inside the blur event handler. You can add the code below to create blur event to validate email address;

email.keyup(validateEmail);

KeyDown event

As shown above add below mentioned code to handle keyup event validation;

name.blur(validateEmail); 

Building client side validation function for email address

Let’s start building the client-side validation function using JQuery. First, inside event handler what client side validations are going to performed needed to be identified. In this case it is the given email field to be client-side validated, You will need to check for empty entries and the email generally accepted formats.

Validation for empty email address

Empty string client-side validation can be performed using Jquery as follows;

//validation for empty emails
 if (email.val() == "") {
 email.addClass("error");
 emailInfo.text("Names cannot be empty!");
 emailInfo.addClass("error");
 return false;
 } else {
 email.removeClass("error");
 emailInfo.text("*");
 emailInfo.removeClass("error");

 }


My first article gives more details about empty string client-side validation. With the above JQuery code in place, you can check for empty email address at client-side. Once you implement this code you will notice, your form doesn’t submit to the server due to an client side error and uses are notified with the error in red color as shown in the picture.

Error - From Register
Error - From Register

Validation for Correct Email format

Client-side Email address format validation is rather complicated and not strait forward. The below mentioned code demonstrates how we can perform it by using JQuery.

//validation for proper email formats
        //testing regular expression
        var a = $("#txtemail").val();

        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        //if it's valid email
        if (filter.test(a)) {
            email.removeClass("error");
            emailInfo.text("*");
            emailInfo.removeClass("error");
            return true;
        }
        //if it's NOT valid
        else {
            email.addClass("error");
            emailInfo.text("Valid E-mail please..!");
            emailInfo.addClass("error");
            return false;
        }

As you can see the above chunk of code uses a very complicated Regular Expression. You must be wondering now how I can write such an expression. It is simple you don’t need to write it you can do a Google search for email validation regular expressions. Google will give you bunch of suggestion to you. You can select the best fit.

As I did the character only validation in my previous article, here I will use a similar logic to validated email formats as shown above code. Once all in place clients can experience the validation effects as shown below image;

Validation for E-mail address
Validation for E-mail address

Let’s check everything together. HTML code will be as follows;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <link href="style.css" rel="Stylesheet" media="all" />
    <!--step one-->

    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

    <!--step four-->
    <script type="text/javascript" src="js/email.js"></script>

</head>
<body>


     <!--step two-->
    <form id="form2" action="" method="post">
    <!--step three-->
    <div>
        E-mail
        <input id="txtemail" type="text" />
        <span id="emailInfo">*</span><br />
        <input id="Submit2" type="submit" value="submit" />
    </div>
    </form>

</body>
</html>

Javascript code will be as follows;

// JScript source code
$(document).ready(function() {
    //global variables
    var form = $("#form2");

    var email = $("#txtemail"); //textbox u are going to validate
    var emailInfo = $("#emailInfo"); //to display error message

    //first validation on form submit
    form.submit(function() {
        //alert("form submitted...!");

        // validation begin before submit
        if (validateEmail()) {

            return true;
        } else {

            return false;
        }

    });
    function validateEmail() {
        //validation for empty emails
        if (email.val() == "") {
            email.addClass("error");
            emailInfo.text("Names cannot be empty!");
            emailInfo.addClass("error");
            return false;
        } else {
            email.removeClass("error");
            emailInfo.text("*");
            emailInfo.removeClass("error");

        }

        //validation for proper email formats
        //testing regular expression
        var a = $("#txtemail").val();

        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        //if it's valid email
        if (filter.test(a)) {
            email.removeClass("error");
            emailInfo.text("*");
            emailInfo.removeClass("error");
            return true;
        }
        //if it's NOT valid
        else {
            email.addClass("error");
            emailInfo.text("Valid E-mail please..!");
            emailInfo.addClass("error");
            return false;
        }
    }

});

© 2012 wecode

More by this Author


Comments 5 comments

hars 4 years ago

can u please tell how to validate a mobile number and if that goes wrong how to highten that particular field displaying an error message..in javascript


wecode profile image

wecode 4 years ago from Australia Author

You can use the same logic. Only difference will be the regular expression. You need to find the exact match for you mobile number pattern. As I created the email validation function create a new function for phone number and call the script in you page


Rob 4 years ago

Hello,

this doesn't work for me when using Internet Explorer 9....

other browsers are fine. Any ideas? :) Thanks!

Thanks

Rob


wecode profile image

wecode 4 years ago from Australia Author

Hello Rob

It works well with IE9. Check security settings where javascript is block or not. Just now I've checked the live demo with a machine with no recommended settings are enabled.

PW


wecode profile image

wecode 3 years ago from Australia Author

You can use the HTML 5 features for mobile validations. Try to use required attribute and the pattern attribute to match with your mobile phone number. HTML 5 will automatically validate and highlight your input box

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working