How can I validate an email address in JavaScript?

How can I validate an email address in JavaScript?

To validate an email address in JavaScript, you can use a regular expression (regex). A regular expression is a pattern that can be used to match character combinations in strings.

Here’s a regex that can be used to validate email addresses:

/^(([^<>()\[\]\\.,;:\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,}))$/

To use this regex, you can use the test() method of the RegExp object. The test() method returns a boolean value indicating whether the pattern was found in the string or not.

Here’s an example of how to use the regex to validate an email address:

function isEmailValid(email) {
  const regex = /^(([^<>()\[\]\\.,;:\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 regex.test(email);
}

console.log(isEmailValid('john@example.com')); // true
console.log(isEmailValid('invalid@email')); // false

Keep in mind that this regex is just a basic email validation. It only checks for the presence of an @ symbol and a valid domain name. There are other more advanced techniques to validate email addresses, such as sending a confirmation email to the address or checking for the existence of the domain’s MX records.

Leave a Reply