This practical, example-based article walks you through 3 different ways to validate an email address in JavaScript.
Using a Regular Expression (Regex)
This is the most common and flexible approach to checking if a string is a valid email address. We can use a regular expression pattern to match the email address format, then test the input string against that pattern.
Example:
const validateEmail = (email) => {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
};
if(validateEmail('[email protected]')){
console.log('[email protected] is a valid email');
} else {
console.log('[email protected] is not a valid email');
}
if(validateEmail('test@example')){
console.log('test@example is a valid email');
} else {
console.log('test@example is not a valid email');
}
Output:
[email protected] is a valid email
test@example is not a valid email
Using the built-in Email API
If you’re working in a browser environment (traditional HTML sites with vanilla JavaScript, React, Next.js, Vue, Angular, etc.), you can use the HTMLInputElement.checkValidity() method with the email input type to check if a string is a valid email address.
Example:
<!-- HTML code -->
<input type="email" id="emailInput">
<button onclick="checkEmail()">Check Email</button>
<!-- JS code -->
<script>
function checkEmail() {
const emailInput = document.getElementById("emailInput");
const isValidEmail = emailInput.checkValidity();
console.log(isValidEmail);
}
</script>
Using a third-party library
There is a plethora of open-source libraries that can help you check whether a given email address is valid or not. One of the most popular ones is validator. You can add it to your project by running:
npm i validator
Then use its validator.isEmail() method to check email addresses as shown below:
import validator from 'validator';
const input1 = '[email protected]';
if(validator.isEmail(input1)){
console.log(`${input1} is a valid email`);
} else {
console.log(`${input1} is not a valid email`);
}
const input2 = 'example@example';
if(validator.isEmail(input2)){
console.log(`${input2} is a valid email`);
} else {
console.log(`${input2} is not a valid email`);
}
Output:
[email protected] is a valid email
example@example is not a valid email