Thursday, October 10, 2013

How to Validate Email Address in JavaScript

While developing a web page in fully HTML controls, you may not be able to use the ASP.NET's controls for example if you want some validation then you can not use the regular expression control there. So there you may need this technique for validating your HTML controls.





Using the Code


Here I will show you how to validate the HTML controls using JavaScript.
Take a text input in html and a form like this

<form action="" method="post"  name="form1" enctype="multipart/form-data" onSubmit="return 
validEmail()">

<input id="emailaddress" name="emailaddress" type="text"  />

And if you Want On Change Validation so just change like this:

<input  name="emailaddress"  type="text" onChange="return validEmail(this)"  />


Now when the filed is change then the JavaScript function validEmail() will be called. Now write the bellow code in this function.


function validEmail(f){

var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(document.forms["form1"]["emailadress"].value.match(mailformat))  
{  
document.form1.emailadress.focus();  
return true;  
}  
else  
{  
elem1 = document.getElementById('emailadressError');
elem1.innerHTML='Not a Valid Email'; 
return false;  
}

}

Now you have successfully validate your HTML controls through JavaScript.

2 comments:

  1. Very Helpful script for my form validation thanks

    http://www.chipincorp.com
    http://www.quick-cheque.com

    ReplyDelete
  2. I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it! would you mind updating your blog with more information Verifications IO

    ReplyDelete