Validate email address using JavaScript regular expression

Posted: Tue, Mar 8 05:32 PM (PST)

Here is the code to validate email address in JavaScript using regular expression.

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;
   }
}

In the forms 'onsubmit' code call javascript:return validate('form_id','email_field_id')

<form id="form_id" method="post" action="action.php" onsubmit="javascript:return validate('form_id','email');">
   <input type="text" id="email" name="email" />
   <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.

Tags: