How to check if a string is a valid email address in JavaScript?

How to check if a string is a valid email address in JavaScript?

ยท

2 min read

Originally Published Here ๐Ÿš€!

To check if a string is a valid email address in JavaScript, we can use a regex expression to match the symbols like @, . and the strings in between them.

TL;DR

// Regular expression to check if string is email
const regexExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/gi;

// String with email address
const str = "johndoe@example.com";

regexExp.test(str); // true

This is the regex expression for matching almost all the test cases for a valid email address in JavaScript.

// Regular expression to check if string is email
const regexExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/gi;

Now let's write a string with email address like this,

// Regular expression to check if string is email
const regexExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/gi;

// String with email address
const str = "johndoe@example.com";

Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,

// Regular expression to check if string is email
const regexExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/gi;

// String with email address
const str = "johndoe@example.com";

regexExp.test(str); // true
  • The test() method will accept a string type as an argument to test for a match.
  • The method will return boolean true if there is a match using the regular expression and false if not.

See the above example live in JSBin.

If you want this as a utility function which you can reuse, here it is,

/* Check if string is email */
function checkIfEmail(str) {
  // Regular expression to check if string is email
  const regexExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/gi;

  return regexExp.test(str);
}

// Use the function
checkIfEmail("johndoe@example.com"); // true
checkIfEmail("johndoe@example."); // false

That's all! ๐Ÿ˜ƒ

Feel free to share if you found this useful ๐Ÿ˜ƒ.