How to validate email address in JavaScript?



In this tutorial, we will learn how to validate an email address using JavaScript.

A computer network's electronic mailbox, often known as an email address, is used to send and receive messages. All email addresses have the same format as in the 1980s.

The email validation process checks to see if an email address is deliverable and legitimate. It quickly executes an algorithm that detects different typos and also whether there are deliberate misdirection or innocent errors. It verifies like Gmail or Yahoo if a certain email address is registered with such reputable domain or not. This increases the effectiveness of your email program and aids in organizing and cleaning up your list of email addresses and safeguards your email sender score.

Following are the methods used to validate an email address using JavaScript.

Using the regular Expression method

Also known as a rational expression, it is defining a search pattern that is a regular expression consists of string of characters. It is typically used in "find and replace"-like operations while comparing patterns in strings. Using regular expressions is more broad method of matching patterns with character sequences.

The following ASCII characters are contained in the personal information part −

  • Uppercase (A-Z )and the lowercase (a-z) letter.
  • All the (0-9) Numeric characters.
  • Special characters like;! - / = ? # $ % & ' * + ^ _ ` { | } ~,
  • Period, dot, or full stop (.)

All with the condition that it cannot be the first or last letter of the email and cannot repeat one after another.

Syntax

var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
   return true;
}
else
{
   return false;
}

The variable mailformat will take the regular expression and check whether the input matches the following format. If it does, the email is valid; else invalid.

Example

In this example, a form is created, and the user enters the email address to be checked through the input section of the form. The email address entered is checked through the regular expression. The regular expression will check if the email address matches the usual format for an email address. This way, the email address is deemed valid or invalid.

<html> <head> <style> li {list-style-type: none; font-size: 16pt; } .mail { margin: auto; padding-top: 10px; padding-bottom: 10px; width: 400px; background : #D8F1F8; border: 1px solid silver; } .mail h2 { margin-left: 38px; } input { font-size: 20pt; } input:focus, textarea:focus{ background-color: lightyellow; } input submit { font-size: 12pt; } .rq { color: #FF0000; font-size: 10pt; } </style> </head> <body onload='document.form1.text1.focus()'> <h2>Validate email address using <i>Regular Expression</i></h2> <div class = "mail"> <h3>Input an email and Submit</h3> <form name = "form1" action = "#"> <ul> <li><input type = 'text' name = 'text1'/></li> <li></li> <li class="submit"><input type = "submit" name = "submit" value = "Submit" onclick = "ValidateEmail(document.form1.text1)"/> </li> <li></li> </ul> </form> </div> <script> function ValidateEmail(inputText) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(inputText.value.match(mailformat)) { document.write("Valid email address!"); document.form1.text1.focus(); return true; } else { document.write("You have entered an invalid email address!"); document.form1.text1.focus(); return false; } } </script> </body> </html>

Calculation of index values method

The lastIndexOf() function returns the string's index (position) at which a given value last appears. From beginning to conclusion, the string is searched. It brings back the index starting at zero (position 0). If the value cannot be retrieved, -1 is returned. Case matters when using the lastIndexOf() function.

The first occurrence's position of a value in a string is returned by the indexOf() function. -1 is returned if this procedure cannot retrieve the value. The case sensitivity of the indexOf() function.

In JavaScript, verify the "@" and "." conditions to validate email addresses.

Syntax

atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
   return false;
}

return true;The first occurrence of "@" is obtained, and the last occurrence of "." is obtained to check the validity of an email address.

Example

In this example, the user enters the email address in the code. To verify the legitimacy of an email address, the first occurrence of "@" and the last occurrence of "." are collected. The indexOf uses this () and lastIndexOf() methods in JavaScript. If the format matches the email ID, it is invalid.

<html> <body> <h2>Validate email address using <i>index values</i></h2> <p id = "root"></p> <script> let root = document.getElementById("root"); var emailID; function validateEmail(emailID) { atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if (atpos < 1 || ( dotpos - atpos < 2 )) { document.write("Please enter correct email ID"); document.myForm.EMail.focus() ; return false; } document.write("Valid email ID!"); document.write("<br>"); return true; } document.write("Email ID entered: abc@gmail.com"); document.write("<br>"); document.write(validateEmail("abc@gmail.com")); document.write("<br>"); document.write("Email ID entered: abc.gmail*com"); document.write("<br>"); document.write(validateEmail("abc.gmail*com")); </script> </body> </html>

In this tutorial, we have encountered two methods to validate an email address. The first method is to use regular expressions. The second method is to find the index values of the special characters used in an email address for validation.


Advertisements