Javascript Email Validation


Try testing the following form with valid and invalid email addresses. The code uses javascript to match the users input with a regular expression.
The Code
function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {
 
      alert('Invalid Email Address');
      return false;
   }
}
The Usage
In the forms ‘onsubmit’ code call javascript:return validate(‘form_id’,'email_field_id’)
<form action="action" id="form_id" method="post" onsubmit="javascript:return validate('form_id','email');">
<input id="email" name="email" type="text" />
   <input type="submit" value="Submit" />
</form>
You should not rely purely on client side validation on your website / web application, if the user has javascript disabled this will not work. Always validate on the server.
Javascript Email Validation Javascript Email Validation Reviewed by Bhaumik Patel on 11:16 PM Rating: 5