What's the best way to validate an email address in JavaScript with a regular expression?

javascript regex validation email-validation 

Nov 17

2 Answers

Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)

const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\[email protected]"]+(\.[^<>()[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/
    );
};

Here's the example of a regular expression that accepts Unicode:

const re =
  /^(([^<>()[\]\.,;:\[email protected]\"]+(\.[^<>()[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i;

But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server-side as well.

Here's an example of the above in action:

const validateEmail = (email) =>
  return email.match(
    /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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,}))$/
  );
};

const validate = () => {
  const $result = $('#result');
  const email = $('#email').val();
  $result.text('');

  if (validateEmail(email)) {
    $result.text(email + ' is valid :)');
    $result.css('color', 'green');
  } else {
    $result.text(email + ' is not valid :(');
    $result.css('color', 'red');
  }
  return false;
}

$('#email').on('input', validate);

And this is the html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="email">Enter an email address: </label>
<input id="email" />
<h2 id="result"></h2>

answered Dec 31


Email validation is a critical part of validating an HTML form. An email is a string or a subset of ASCII characters separated into two parts by @ symbol. The first part contains personal information while the other contains the domain name at which the email is registered.

The personal information part can contain the following ASCII characters:

  • Letters: Uppercase and lowercase letters (A-Z and a-z)
  • Digits: Numeric characters (0-9)
  • Hyphens: Special characters - ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • Dots: Period, dot, or full stop (.) with the condition that it cannot be the first or last letter of the email and cannot repeat one after another.

One of the most popular ways of validating email in JavaScript is by using regular expressions. JavaScript uses regular expressions to describe a pattern of characters. 

email.js

function ValidateEmail(input) {
  	var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-][email protected][a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  	if (input.value.match(validRegex)) {
    	alert("Valid email address!");
    	document.form1.text1.focus();
    	return true;
  	} else {
    	alert("Invalid email address!");
    	document.form1.text1.focus();
    	return false;
  	}
}

This file contains the JavaScript code that we need for email validation. We are using regular expressions to validate the email at the client-side of a web application.

email.html

<!DOCTYPE html>
<html lang="en">
  	<head>
    	<meta charset="utf-8" />
    	<title>JavaScript Email Validation</title>
    	<link rel="stylesheet" href="email.css" type="text/css" />
  	</head>
  	<body onload="document.form1.text1.focus()">
    	<div class="mail">
      		<h2>Input an email address</h2>
      		<form name="form1" action="#">
        		<ul>
          			<li><input type="text" name="text1" /></li>
          			<li>&nbsp;</li>
          			<li class="validate">
            			<input
              			type="submit"
              			name="validate"
              			value="Validate"
              			onclick="ValidateEmail(document.form1.text1)"
            			/>
          			</li>
          			<li>&nbsp;</li>
        		</ul>
      		</form>
    	</div>
    	<script src="email.js"></script>
  	</body>
</html>

This file contains the base HTML code that has all the elements defined for this webpage.

We hope you understood how to implement email validation in JavaScript after going through this article. This is a relatively simple topic that gets used in various kinds of web applications.

answered Dec 31


Login and Submit Your Answer
Browse other questions tagged  javascript  regex  validation  email-validation or ask your own question.