You can use regular expressions to validate an email address in JavaScript. Here's a code snippet that checks if an email address is valid:
javascriptfunction validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
In this code, validateEmail
is a function that takes an email address as its argument. The regular expression ^[^\s@]+@[^\s@]+\.[^\s@]+$
checks if the email address is in a valid format. Here's a breakdown of the regular expression:
^
- Start of string[^\s@]+
- One or more characters that are not whitespace or @@
- The @ symbol[^\s@]+
- One or more characters that are not whitespace or @\.
- A literal period (escaped with a backslash)[^\s@]+
- One or more characters that are not whitespace or @$
- End of string
The test
method of the regular expression object checks if the given email address matches the regular expression. If the email address is valid, the function returns true
, otherwise it returns false
.
Here's an example of how to use the validateEmail
function:
javascriptconst email = 'example@example.com';
if (validateEmail(email)) {
console.log('Email is valid');
} else {
console.log('Email is invalid');
}
In this code, email
is a string containing an email address. The if
statement checks if the email address is valid using the validateEmail
function, and logs a message to the console indicating whether the email is valid or invalid.
Javascript,Javascrip Interview Questions and Answers,JavaScript Tutorial
Comments
Post a Comment