This
is one of common requirement while working with web application, we can
validate email address on both client and server side. But it is always
recommended to validate email on client side. On client side we can validate email address in jQuery
with the help of regular expression.
In
this post, I'll show how you can validate email on client side with the help of
regular expression.
First
of all lets create one text box where user can enter an email and one button to
test the email (entered by user) is valid or not.
//Define textbox
and button in HTML.
Enter Email Address: <input type='text' id='txtEmail'/>
<input type='submit' id='btnEmailValidate' Value='Test Email' />
|
Now
write the script to validate the email entered by user.
//On Ready
method invoke button click to validate email.
$(document).ready(function (e) {
$('#btnEmailValidate').click(function () {
var emailText = $('#txtEmail').val();
if (isValidEmail(emailText))
{
alert('This is a valid Email');
}
else {
alert('This is an invalid Email');
}
});
});
//Method to test entered email against Regex.
function
isValidEmail(emailText) {
var emailRegex = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return
emailRegex.test(emailText);
}
|
Check
live Demo on jsfiddle.
|
Comments
Post a Comment