JAVASCRIPT
Validate Email Addresses
Learn to validate email addresses in web forms using a comprehensive regular expression in JavaScript, ensuring correct format and preventing common errors.
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("[email protected]")); // false
How it works: This JavaScript snippet provides a robust regular expression to validate email addresses. The pattern matches common email structures, including alphanumeric characters, dots, underscores, percents, pluses, and hyphens before the '@' symbol, followed by a domain name and a top-level domain of at least two characters. The `test()` method of the RegExp object efficiently checks if a given string conforms to this pattern.