Register Login

Validate Email Address in JavaScript

Updated Feb 08, 2021

Apart from developing websites, JavaScript is also used for validating email addresses. This is a very important step while validating an HTML form. In this post, we will discuss the process of email validation using JavaScript.

Now we will look at the three ways to validate an email address. They are –

1) Email Validation Using Regular Expression

What is Regular Expression?

A regular expression is a sequence of characters that are used for defining a search pattern. They are usually used for pattern matching using strings.

The correct regular expression pattern for an email id is -

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

OR

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

You can choose any one of the above.

Complete Code:

<!doctype html><html><head><meta charset="utf-8">
<title>How to validate email address in javascript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function validateEmail() {
	var myemail = $("#email").val();
	//var reexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	var reexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	
	if (reexp.test(myemail) == true){
		$('#msg').html(myemail + ' is Valid Emal Id');
		$('#msg').css("color", "green");
	}else{
		$('#msg').html(myemail + ' is not Valid Email Id');
		$('#msg').css("color", "red");
	}
}
	
$(document).ready(function(){
	$("#checkemail").click(function(){
    	validateEmail();
  	});
});
</script>
</head>
<body>
<p>
  <label for="email">Email:</label>
  <input type="text" name="email" id="email">
	<div id="msg"></div>
</p>
<p>
  <input type="button" name="checkemail" id="checkemail" value="Button" >
</p>
</body>
</html>

Code Explanation

In the code written above, we are obtaining the value of an input field email and assigning it in the variable email. Then, with the help of a regular expression stored in variable reexp, we are validating the email entered by the user. The code also uses the “test() function”. If the value returned by this method is True, then the email address is valid. If the value returned is False, the email id is invalid.

2) Simple Email Validation by Checking ‘@’ and ‘.’

In case you want a simpler process of email validation, then you can check for “@” and “.” This is because all valid email addresses will have these two characters in them.

So, you can check the existence of these characters in the following ways –

  • Determine the location of the last “@”, and the last “.” Character
  • Ensure that the “@” is not the first character of the email
  • Ensure that the “.” appears after the “@”. There must be one character between them
  • There must be at least one character after the “.”

You can use the regular expression to check the presence of “@” and “.”

Code Example:

<!doctype html><html><head>
<title>How to validate email address in javascript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function validateEmail() {
	//  Taking value of input field in variable myemail
	var myemail = $("#email").val();
	
	// taking the position of @ from email string in variable at
	var at = myemail.lastIndexOf("@");
	
	// taking the position of . from email string in variable .
    var dot = myemail.lastIndexOf("."); 
	
	// 1. position of "@" & ". greater than 0 and position of @ is greater than 1
	if (at > 0 && dot > at + 1 && dot < myemail.length - 1){
		$('#msg').html(myemail + ' is Valid Emal Id');
		$('#msg').css("color", "green");
	}else{
		$('#msg').html(myemail + ' is not Valid Email Id');
		$('#msg').css("color", "red");
	}
}
	
$(document).ready(function(){
	$("#checkemail").click(function(){
    	validateEmail();
  	});
});

</script>
</head>
<body>
<p>
  <label for="email">Email:</label>
  <input type="text" name="email" id="email">
	<div id="msg"></div>
</p>
<p>
  <input type="button" name="checkemail" id="checkemail" value="Button" >
</p>
</body></html>

Code Explanation

In the above example, we are obtaining the email address value from the user and storing it in the myemailvariable. Then the code checks the position of “@” and “.” using the lastIndexOf() method. Inside an If block, it is checked whether the position of “.” is greater than “0”. Also, the code checks if the position of @ is greater than 1. If both these conditions are satisfied, then the entered email address is valid. Otherwise, it will be considered invalid.

However, this process is not a perfect email id validation because only the position of “@” and “.” is checked.

Simple Email Validation Using Regular Expression

We can use a regular expression to check the position of “@” and “.” in the given string.

Regular expression pattern to check “@” and “.” –

/\S+@\S+\.\S+/

Code Example:

<!doctype html><html><head>
<title>How to validate email address in javascript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function validateEmail() {
	var myemail = $("#email").val();
	reexp = /\S+@\S+\.\S+/;
	
	if (reexp.test(myemail) == true){
		$('#msg').html(myemail + ' is Valid Emal Id');
		$('#msg').css("color", "green");
	}else{
		$('#msg').html(myemail + ' is not Valid Email Id');
		$('#msg').css("color", "red");
	}
}
	
$(document).ready(function(){
	$("#checkemail").click(function(){
    	validateEmail();
  	});
});

</script>
</head>
<body>
<p>
  <label for="email">Email:</label>
  <input type="text" name="email" id="email">
	<div id="msg"></div>
</p>
<p>
  <input type="button" name="checkemail" id="checkemail" value="Button" >
</p>
</body></html>

Code Explanation

In the code above, the email address entered by the user is stored in the variable myemail. A regular expression is also assigned in the variable reexp. Then, using the test() function, the email address is checked against the regular expression. This checks the position of “@” and “.” If the function returns True, the email is valid. If it returns False, the entered email id is invalid.

3) HTML 5 Email Validation

HTML 5 has an in-built email validation method. For this, you only need to specify the input field as type email.

Code Example:

<!doctype html><html><head>
<title>HTML 5 Email Validation</title>
</head>
<body>
<form action="Validate-Email-Javascript-4.html" method="get" name="form1" id="form1">
<p>
  <label for="email">Email:</label>
  <input type="email" name="email" id="email" required>
</p>
<p><input type="submit" name="submit" id="submit" value="Submit"></p>
</form>
</body></html>

Email Validation HTML5

Code Explanation

In the above example, you can see that we have just declared the input type field as email

<input type="email" name="email" id="email" required>

As this field is set to required, the in-built validation will take place. Therefore, if the user enters something that does not resemble an email address, this message will be displayed.

What is Validation?

Validation is the process of authenticating a user using an HTML form. There are 2 types of form validation –

  • Server Side validation
  • Client-side validation

Server-side Validation

This type of data validation is conducted by the web-server. This happens after data is sent to the server. The data is validated by server-side scripting languages such as PHP and ASP.Net. After validation, the feedback is sent to the client. This is done to protect the data from malicious attacks.

Client-side Validation

This process is conducted by the browser before the data is sent to the server. The entire validation takes place on client browser using scripting languages like JavaScript, HTML5 or VBScript. So, if a user enters an invalid email address, the browser will quickly notify him/her.

JavaScript can be used to validate a form on the client-side. This is done to speed up the data processing on the server-side. That’s why most programmers and developers prefer this method. We will talk a lot about client-side validation here.

What is an Email string?

An email string is divided into two parts by a @ symbol and a “.”. The part before the @ is can be considered as personal information, which can be up to 64 characters long. The part after the “.” is the domain. This part can be up to 253 characters.

For example, myname@company.org.

The personal information part has the following ASCII characters –

  • Uppercase characters (A-Z) and lowercase characters (a-z)
  • Digits between 0 to 9
  • Characters among these - ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • The character. ( period or full stop)

The domain name (com, org, net or in) part consist of letters, digits, dots and hyphens.

Example of valid email id

  • mysite@gmail.com
  • my.blog@ourearth.org
  • main_site@you.me.net

Example of invalid email id

  • mywebsite.ourearth.com (@ is not present)
  • myblog@.com.my (A top Level domain cannot start with ".")
  • @abc.me.org (There character before @)
  • myblog112@gmail.b (".b" is an invalid domain name)
  • myblog@.org.org (A top Level domain cannot start with dot ".")
  • .my_website@mysite.org (No email id must start with ".")
  • mysite()*@yahoo.com (The regular expression can only allow characters, digits, dash or underscore)
  • my_website..007@gmail.com (No double dots allowed)

Which is the Best Option for Form Validation?

A combination of Server-side validation and HTML5 or Javascript can be considered the best option. This is because even if JavaScript is disabled in a browser, HTML5 will still work as all modern browsers support it.

But older versions of the browsers may not support HTML5. In those cases, server-side validation is essential.

Conclusion

By now, you would have understood the different ways of validating an email address. This type of validation is needed when you are creating an online profile or account. As discussed, JavaScript validation is not a perfect process as it can be disabled in the browser. So, always check whether JS is enabled in your web browser.

At the end of the day, HTML5 and server-side validation will help you to run things smoothly.


×