jQuery: email validation

E-mail addresses are basically made up of three components: a username, the at symbol ('@') and a domain name. Their form is generally username@domain.ext. Validating an e-mail address is usually performed by creating a regular expression to be compared with the user's input. However, this kind of validation is not very accurate when it comes to explain to the user why his / her e-mail address has been rejected. An error message that simply says Invalid e-mail is not very useful, because the user might have written a wrong domain name or missed the at symbol. I think it's better to validate each component on its own. In this post I'm going to show you how to accomplish this task with jQuery.

$('#test').submit(function(e) {
  
    var email = $(this).find('#email').val();
    var at = '', name = '', domain = '', errors = '<ul class="errors">';
    
    
    at = email.charAt(email.indexOf('@'));
    
    name = email.substring(0, email.indexOf('@'));
    
    domain = email.substring(email.indexOf('@')+1, email.length);
    
    // code continues
});

First, we extract all the components of an e-mail address and we store them in the at, name and domain variables. Then we validate them separately:

// code continues

    if(at != '@') {
    
    
      errors += '<li>Missing @</li>';
    
    
    }
    
    if(!/^([a-zA-Z0-9_\.\-])+$/.test(name)) {
    
      errors += '<li>Invalid username.</li>';
      
    }
    
    if(!/^(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(domain)) {
    
      errors += '<li>Invalid domain.</li>';
    
    
    }
    
    errors += '</ul>';
    
    if(/<li>/.test(errors)) {
    
      $(errors).appendTo('#test');
    
    
    } else {
    
    
      $('<p class="success"/>')
      .text('Valid e-mail!').appendTo('#test');
    
    }
    
    
  
    e.preventDefault();

The final check on the errors variable is performed to test whether there are validation errors or not. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.