Validate email address
Here is a simple way to validate an email address using a regular expression:
function validateEmail(email) {
const re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return re.test(email);
}
This regular expression checks for the following:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-), underscore (_), percent (%), plus sign (+)@
matches the @ symbol[a-zA-Z0-9.-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-)\.
matches a period (.) character[a-zA-Z]{2,}
matches the domain extension (it must be at least 2 characters long)$
matches the end of the string
You can use this function like this:
const email = '[email protected]';
if (validateEmail(email)) {
console.log('Email is valid');
} else {
console.log('Email is not valid');
}
This regular expression does not check if the email address actually exists or is in use, it only checks if the format of the email address is correct.
Here are some examples of valid and invalid email addresses:
Valid:
Invalid:
- @example.com (missing local part)
- example..com (multiple dots in a row)
- [email protected] (missing domain)
- example@example (missing top-level domain)
- [email protected] (multiple dots in a row)
Keep in mind that this is a basic validation and it's not foolproof. It's always a good idea to use a more advanced validation library or service if you need to validate email addresses in a production environment.