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.