To validate an email address in JavaScript, you can use a regular expression (regex) pattern. Here's an example of a basic regex pattern for email validation:
function validateEmail(email) {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
The validateEmail() function takes an email address as an argument and returns true if the email is valid, and false otherwise.
The regular expression pattern /^[^\s@]+@[^\s@]+\.[^\s@]+$/ is made up of several parts:
^ - Matches the start of the string.
[^\s@]+ - Matches one or more characters that are not whitespace or the @ symbol. This matches the local part of the email address (i.e. the part before the @ symbol).
@ - Matches the @ symbol.
[^\s@]+ - Matches one or more characters that are not whitespace or the @ symbol. This matches the domain part of the email address (i.e. the part after the @ symbol but before the last .).
\. - Matches the . character that separates the domain name and top-level domain.
[^\s@]+ - Matches one or more characters that are not whitespace or the @ symbol. This matches the top-level domain (e.g. com, net, org, etc.).
$ - Matches the end of the string.
To use the function, you can pass an email address as an argument and check the return value:
const email = "test@test.com";
if (validateEmail(email)) {
console.log("Valid email address.");
} else {
console.log("Invalid email address.");
}
This code will output "Valid email address." if the email is valid, and "Invalid email address." if it is not.
Comments (0)