← Back to all snippets
JAVASCRIPT

Validate Email Address Format

A robust JavaScript regex snippet to accurately validate common email address formats, ensuring correct syntax for user inputs in web forms and applications.

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

function isValidEmail(email) {
  return emailRegex.test(email);
}

// Examples:
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid-email")); // false
console.log(isValidEmail("user@localhost")); // false (no top-level domain of at least 2 chars)
How it works: This regex pattern validates common email address formats. It ensures a username part composed of alphanumeric characters, dots, underscores, percents, plus, or hyphens. This is followed by an '@' symbol, then a domain name (alphanumeric, dots, hyphens), and finally a top-level domain of at least two alphabetical characters. The `test()` method of the regex object returns true if the string matches the pattern, otherwise false.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs