Summary: In this JavaScript tutorial, you will learn with example how to validate email addresses in JavaScript.

To validate an email address in JavaScript, you can use a regular expression, which is a sequence of characters that forms a search pattern. A regular expression can be used to check whether a string contains the pattern or not.

Here’s an example of how to use a regular expression to validate an email address in JavaScript:

function validateEmail(email) {
  const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
  return re.test(String(email).toLowerCase());
}

console.log(validateEmail('john@example.com'));  // returns true
console.log(validateEmail('john@example'));  // returns false

In this example, the validateEmail() function takes an email address as an argument and uses a regular expression to check if it’s a valid email address or not. The regular expression checks for the following:

  • The email address should contain one or more characters before the @ symbol.
  • The email address should contain a @ symbol.
  • The email address should contain one or more characters after the @ symbol, followed by a . and one or more characters (e.g., .com, .net, etc.).

The test() method is used to test whether the regular expression matches the provided email address. If the email address is a match, the test() method returns true, otherwise it returns false.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply