Themeforest

Email Validation Using jQuery

A client recently wanted to include validation on their website registration form that would not only check that the input text was a genuine email address but also to disallow registration of any “free” email addresses.

Using jQuery we can easily add this to the website by creating a regular expression, which checks for email addresses such as yahoo, gmail, hotmail, etc prior to submitting the form to the server. The regular expression can be adapted to reject any domain specified.

First add the form to your website using standard HTML code:

<form method="post" name="form1" action="">
  <fieldset>
   <label>Email Address:</labe>
   <input type="text" name="UserEmail" id="UserEmail" value="" size="32" />
   <input type="submit" value="Submit" id="btn-submit" />
  </fieldset>
</form>

Step 1 – Initiate the jQuery Validation

After adding jQuery to your website we set up the code that will perform the validation when the submit button is clicked – first clearing any existing error messages from previous attempts:

$(document).ready(function() { 

    $('#btn-submit').click(function() {  

        $(".error").hide();
        var hasError = false;

    });
});

Step 2 – Check that the Input Field is Not Empty

For the first step of the validation we want to add the jQuery code that will check if there is any text in the input field and if not return the appropriate error message and stop the form being submitted:

$(document).ready(function() { 

    $('#btn-submit').click(function() {  

        $(".error").hide();
        var hasError = false;

        var emailaddressVal = $("#UserEmail").val();
        if(emailaddressVal == '') {
            $("#UserEmail").after('<span class="error">Please enter your email address.</span>');
            hasError = true;
        }

        if(hasError == true) { return false; }

    });
});

Step 3 – Check that the Entered Text is a Valid Email Address

Our first regular expression will check to make sure that the entered text is a valid email address – i.e. contains at least one “.”, an “@” symbol and an appropriate top-level domain suffix (e.g. .com, .net, etc):

$(document).ready(function() { 

    $('#btn-submit').click(function() {  

        $(".error").hide();
        var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        var emailaddressVal = $("#UserEmail").val();
        if(emailaddressVal == '') {
            $("#UserEmail").after('<span class="error">Please enter your email address.</span>');
            hasError = true;
        }

        else if(!emailReg.test(emailaddressVal)) {
            $("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
            hasError = true;
        }

        if(hasError == true) { return false; }

    });
});

Step 4 – Block or Prevent Free Email Addresses – e.g. yahoo.com, gmail.com and hotmail.com

The 2nd regular expression will now check the entered text against our pre-defined domain names – in this case yahoo.com, gmail.com and hotmail.com. Once again an error message is displayed and the form submission stopped if the email address matches one of the domains:

$(document).ready(function() { 

  $('#btn-submit').click(function() {  

    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var emailblockReg =
     /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w-]+\.)+[\w-]{2,4})?$/;

    var emailaddressVal = $("#UserEmail").val();
    if(emailaddressVal == '') {
      $("#UserEmail").after('<span class="error">Please enter your email address.</span>');
      hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
      $("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
      hasError = true;
    }

    else if(!emailblockReg.test(emailaddressVal)) {
      $("#UserEmail").after('<span class="error">No yahoo, gmail or hotmail emails.</span>');
      hasError = true
    } 

    if(hasError == true) { return false; }

    });
});

The above example can easily be configured to reject (or even accept) any specified email address. To see it in action:

Check out our online demo of Email Validation Using jQuery.

25 Comments

  • Hi! I’m developing a PHP application and your post was very useful! PHP can validate emails (with FILTER_VAR), but i needed to use jQuery because it is typed by users and use resources from server every time a email is typed was making the system slow!
    Thank you!

  • Awesome article, simple steps and implementation. I decided to use a change event though, so the user would get instant feedback when typing in the form and that worked suh-weeet! Thanks, i’ll be checking out some more of your stuff!

  • This was an awesome tutorial, exactly what I was looking for. Thank you for sharing a bit of your genius!

  • Hi lee..how can we validate like a person registering to a website with the email id with the same email id that already exists(been used).

    • Hi,

      That would need to be handled server-side and the email checked against your records

  • Thanks for the code! I only have one suggestion, if in fact someone hasn’t already mentioned it. In the process of using this code, it occurred to me that I could hit return/enter while in the form, and it was skip the validate process (since it’s only set to validate upon clicking the submit button). My suggestion is that instead of:
    $(’#btn-submit’).click

    Select the form with the jQuery selector and use the .submit method.
    $(”#form”).submit

    This way it’ll still validate when using the return key, or if the submit button is used, assuming the submit button is in the form.

    Thanks a lot for the code, very useful!

    • Hi,

      Good suggestion

  • Just a suggestion for the code in step 3 would be to return a true value by default and false only is it is not validated.

    Great examples all in all. Thanks for that.

  • (!emailReg.test(emailaddressVal) I did not catch up the idea of this line. I looked for .test() method and no results so far

    • test() is a standard javascript function for checking strings against regular expressions

  • Thanks a lot for such a nice tutorial! It really helped me a lot :)

    • Hi,

      Thanks. Glad it helped

  • Hey pro, much appreciated your solution. its easy and simple. I was just thinking, if the error message can be shown as a label hanging down the email input area….

    • Hi,

      That is just a CSS issue – just change the error message background image

  • Thanks for this article. Just a comment on your method of clearing previous errors. You use this line:

    $(".error").hide();

    which hides previous error DIVs, but the text remains in the DOM. It seems like a better solution would be:

    $(".error").remove();

    Which actually removes the previous error DIVs from the DOM.

    • Hi Scott – you are correct. It should be remove()

  • Thanks for good jquery, i like ur effective solution.. please can u update sending email function using jquery

    • Hi Hariis – update which part?

  • Thanks for this, great tutorial and very easy to implement =D

  • Nice tutorial! i would like to apply “fade in effect” when the message error appears, i’m having hard times how to implement it so…

  • works like a charm! Thanks :)

  • [...] For this tutorial we assume you know how to create the HTML form and add jQuery to your site. For samples you can refer to previous posts – check passwords using jQuery or email validation using jQuery. [...]

  • Excellent! Looks great especially after adding speeds to the hide and show functions.

  • thank you for your tutorial.
    your teaching is wonderful !!!!

    the post is a hope for me.
    really.

  • I was searching for article on this topic and i was lucky to find yourblog.I will also send this url to my friend so he can also read and complete our project.hope to get some good marks in this project.Thank you for this awesome post.

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags