← Back to all snippets
JAVASCRIPT

Validating Email Addresses with Regex

Learn to validate email address formats in JavaScript using a robust regular expression, ensuring user input meets standard email criteria for forms.

const isValidEmail = (email) => {
  // Regex for basic email validation (RFC 5322 standard is complex, this is practical)
  const emailRegex = new RegExp(
    /^(([^<>()[\\].,;:\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 emailRegex.test(email);
};

console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid-email"));     // false
How it works: This JavaScript snippet defines a function `isValidEmail` that uses a regular expression to test if a given string conforms to a common email address format. The regex checks for a pattern including an alphanumeric local part, an '@' symbol, and a domain name with a top-level domain. It's a practical balance between strictness and avoiding over-complexity of the full RFC standard.

Need help integrating this into your project?

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

Hire DigitalCodeLabs