Jquery Email Validation using Regular Expression

Jquery Email Validation using Regular Expression

In internet Email ID acts like an identity token. Whether you do register for a Job site or Forum a valid Email ID is mandatory. During registration process there is a possibility that user can provide invalid Email ID. So to prevent spam we use Email Validation. In Web Technology Email validation can be done using both Client & Server side scripts. But if we will look into performance it is more better to use client resources to validate an email. As you know jquery is one of the most powerful Client-side scripting language. In this demo app I created a Jquery Email Validation using Regular Expression.

Look at the code below here in HTML body part I have a input box with a submit button. Onclick of submit button I am calling a jquery function validEmail($email) inside the jquery document.ready() method. This function accepts email id as a parameter. To verify the email id inside the validEmail() function I am using regular expression with jquery test method. You can do the same using jquery match method too.

To run the below example. Copy the Codes to a notepad file. Save it as a HTML file. Then Open it in your browser. Here to refer jquery library file I am using CDN link. Make sure while running this demo app you are with internet connectivity.

jquery-email-validation.htm

<!Doctype html>
<html>
<head>
<title>Jquery Email Validation using Regular Expression</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/*Email Validation Function using Regular Expression*/
function validEmail($email) {
var emailReg = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test($email) ) {
alert('Invalid Email ID.');
} else {
alert('Valid Email ID.');
}
}
/*Submit Button Click event using Jquery*/
$("#btnSubmit").click(function() {
var email = $('#txtEmail').val().trim();
if (email) {
validEmail(email);
}
});
});
</script>
</head>
<body>
<input type="text" id="txtEmail" />
<button id="btnSubmit">Submit the Form</button>
</body>
</html>