JAVASCRIPT

Validate Email Addresses with a Robust Regex Pattern

Learn to validate email addresses effectively in JavaScript using a comprehensive regular expression pattern for client-side and server-side input checks.

function isValidEmail(email) {
  // RFC 5322 compliant, with some common-sense simplifications for web
  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);
}

// Usage:
// console.log(isValidEmail("[email protected]")); // true
// console.log(isValidEmail("invalid-email")); // false
// console.log(isValidEmail("[email protected]")); // true
How it works: This JavaScript function `isValidEmail` uses a regular expression to check if a given string adheres to a common email format. The regex is designed to be largely compliant with RFC 5322, allowing for a wide range of valid email structures, including alphanumeric characters, dots, hyphens, and common domain formats. It returns `true` for valid emails and `false` otherwise, making it ideal for form validation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs