Objectives and outcomes

In this tutorial we are going to learn email validation in javascript. To validate email we generally use both type of validation i.e. basic as well as data-format validation. As email is text input so we first check for empty or null input which is the part for basic validation and then we check for position of dots and @ in it which is the part of data-format validation.



HTML code:

<html>
<body>
<form name="form2" onSubmit="return(form_valid());" method="post">
Email:&nbsp;<input type="text" name="email"><br/>
<br/>
<input type="submit" value="submit">
<br/>
</form>
</body>
</html>





Javascript:

<script type="text/javascript">
//  Basic validation
if(document.forms["form2"]["email"].value == "")
{
alert("please provide your email!!");
document.forms["form2"]["email"].focus();
return false;
}
	
//   Data-format validation
	
var emailID = document.forms["form2"]["email"].value;
var atpos = emailID.indexOf("@");
var dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.forms["form2"]["email"].focus() ;
return false;
}  // --  Data-format validation
</script>