Tip: Validate email without regular expression

We can perform a very basic validation of email address with JavaScript by implementing the following three rules

  • The email address must have @ character
  • The email address must have .(dot) character
  • There must be at lease 2 characters between @ and .(dot)

The sample code blow validates email address by implementing the above three rules

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript"> 
	function validate(){
		var t=document.getElementById('email');
		var x=t.value.indexOf('@');
		var y=t.value.lastIndexOf('.');
 
		if(x==-1 || y==-1 || (x+2)>=y){
			alert('Email address is not valid');
		}
		else{
			alert('Email is ok');
		}
	}
 </script>
<title>Email validation with JavaScript</title>
</head>

<body>
	<input type="text" name="email" id="email" />
    <input type="button" value="Validate" onclick="validate()" />
</body>
</html>

There are many techniques of validating email address, each validation method has its own pros and cons. The above method doesn't require understanding of regular expressions

 

More Javascript tips