Thursday, October 4, 2012

Validate email address using jQuery

This is a very basic functionality to validate the email address. In this post, I will show you how to validate the email address using jQuery. To validate the email address, I have created a separate function which based on email address, returns true or false. Email address validation is done using regular expression.
function validateEmail(sEmail) {     var filter = /^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$/;     if (filter.test(sEmail)) {         return true;     }     else {         return false;     } }​ 
One just need to make a call to this function to validate the email address. For demo, I have used on click event of button. But It can be used on blur event of textbox or any another event.
$(document).ready(function() {    $('#btnValidate').click(function() {         var sEmail = $('#txtEmail').val();         if ($.trim(sEmail).length == 0) {             alert('Please enter valid email address');             e.preventDefault();         }         if (validateEmail(sEmail)) {             alert('Email is valid');         }         else {             alert('Invalid Email Address');             e.preventDefault();         }     }); }); 
See result below.


See Complete Code
http://jsfiddle.net/jquerybyexample/FDMzf/
http://jsfiddle.net/jquerybyexample/PUkXV/
http://jsfiddle.net/jquerybyexample/DxPuU/
http://jsfiddle.net/jquerybyexample/LQAYy/
Feel free to contact me for any help related to jQuery, I will gladly help you.

No comments:

Post a Comment