Check email id is valid
Here's a simple way to check if an email ID is valid using a regular expression:
Regex Pattern:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Explanation:
^
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 and only contain letters)$
matches the end of the string
Example Code:
function isValidEmail(email) {
const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return regex.test(email);
}
Usage:
const email = "[email protected]";
if (isValidEmail(email)) {
console.log("Email is valid");
} else {
console.log("Email is not valid");
}
This code will return true
if the email ID is valid and false
otherwise.
Note that this is not foolproof, as it's possible for an email ID to be valid but not actually exist. Additionally, this regex pattern does not check for things like whether the email ID is already in use or whether the domain exists.