Answer: You can validate an email address in JavaScript with regular expression.
Email validation in Javascript checks if the email address is in the correct format before using or storing it. There are a few more methods to validate an email address in Javascript such as Built-in HTML5 email validation, and email validator libraries. We will discuss these methods in this blog in detail.
Table of Contents:
Importance of Email Address Validation
- Ensure data accuracy: Validate that the user provides correctly formatted email addresses, reducing errors and improving data quality.
- Enhance user experience: Provides immediate feedback, allowing users to correct mistakes quickly.
- Increases Security: Prevents harmful input, reducing the risk of attacks such as SQL injection.
- Reduces Spam: Filters out invalid email addresses, improving the quality of data and reducing spam.
Criteria for Valid Email
- Presence of “@”: The email must contain the symbol “@”
- Valid domain: There should be a valid domain after “@” (eg:gmail.com).
- Non-Empty local part: The part before “@” should not be empty.
- Valid characters: The email should only contain valid characters such as letters, numbers, dots, hyphens, and underscores.
- Top-level domain: The email should have a top-level domain (e.g., .com, .org, .net, .in).
Methods to Validate Email Addresses in Javascript
Using Javascript expressions we can validate the email addresses. Here are some of the most common methods to validate the email address.
Method 1: Using Regular Expression (Regex) to Validate Email Addresses in Javascript
You can use a regular expression to match the email with the valid string format. It checks with the pattern in the regex and the alert message pops up.
Example:
<form id="emailForm">
<input type="text" id="email" placeholder="Enter your email">
<button type="submit">Submit</button>
<p id="errorMessage" style="color: red; display: none;">Please enter a valid email address.</p>
</form>
<script>
document.getElementById('emailForm').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent form submission
const email = document.getElementById('email').value;
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (emailPattern.test(email)) {
alert("Valid email address!");
} else {
document.getElementById('errorMessage').style.display = 'block';
}
});
</script>
Output:
Explanation: You can enter the email address for validation. After the validation process, you get a success message or error alert.
Method 2: Using HTML5 Built-in Email Validation in JavaScript
You can use the built-in attribute <type=“email”> to validate the email address. You can also use the required attribute to make sure the user is not leaving the field empty.
Example:
<form id="emailForm">
<input type="email" id="email" placeholder="Enter your email" required>
<button type="submit">Submit</button>
<p id="errorMessage" style="color: red; display: none;">Please enter a valid email address.</p>
</form>
<script>
document.getElementById('emailForm').addEventListener('submit', function(e) {
e.preventDefault();
const email = document.getElementById('email');
if (email.validity.valid) {
alert("Valid email address!");
} else {
document.getElementById('errorMessage').style.display = 'block';
}
});
</script>
Output:
Explanation: When you enter the input, the built-in attribute checks the email address. And you will be notified with an alert message.
Method 3: Using the Email-Validator Library to Validate Email Addresses in Javascript
You can use EmailValidator.validate(email) to validate the email address. The libraries can be installed from the npm packages.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Email Validator Example</title>
</head>
<body>
<h2>Email Validator Example</h2>
<input type="text" id="email" placeholder="Enter your email">
<button onclick="validateEmail()">Validate</button>
<p id="result"></p>
<script>
function validateEmail() {
var email = document.getElementById("email").value;
var result = document.getElementById("result");
var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (emailPattern.test(email)) {
result.style.color = "green";
result.innerHTML = "Valid Email";
} else {
result.style.color = "red";
result.innerHTML = "Invalid Email";
}
}
</script>
</body>
</html>
Output:
Explanation: You can enter the email address in the input field. The library checks the input and throws the alert message.
Method 4: Validate Multiple Email Addresses in Javascript
You can use regular expressions to validate the multiple email addresses. The input is given as multiple email addresses with commas and spaces between them. You can validate, by looping through them one by one.
Example:
<form id="emailForm">
<input type="text" id="emails" placeholder="Enter emails separated by commas">
<button type="submit">Submit</button>
<p id="errorMessage" style="color: red; display: none;">Please enter valid email addresses separated by commas.</p>
</form>
<script>
document.getElementById('emailForm').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent form submission
const emails = document.getElementById('emails').value.split(',').map(email => email.trim());
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
let allValid = true;
// Loop through each email and validate
emails.forEach(email => {
if (!emailPattern.test(email)) {
allValid = false;
}
});
if (allValid) {
alert('All email addresses are valid!');
} else {
document.getElementById('errorMessage').style.display = 'block';
}
});
</script>
Output:
Explanation: When you give multiple email addresses as input, the code validates them using the regular expression. If the email address is valid users are alerted with a message.
Method 5: Using include() Function to Validate Email Addresses in Javascript
You can use include() to check whether the substring is present within the string. So here, we use this function to check for basic characters in the email address.
Example:
<form id="emailForm">
<input type="text" id="email" placeholder="Enter your email">
<button type="submit">Submit</button>
<p id="errorMessage" style="color: red; display: none;">Please enter a valid email address.</p>
</form>
<script>
document.getElementById('emailForm').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent form submission
const email = document.getElementById('email').value;
// Check if the email contains "@" and "."
if (email.includes('@') && email.includes('.')) {
alert('Valid email address!');
} else {
document.getElementById('errorMessage').style.display = 'block';
}
});
</script>
Output:
Explanation: When you give the email address as the input, the code checks for the basic characters. If they are not present, it shows an error message.
Method 6: Using fetch() to Validate Email Address via API in JavaScript
You can validate the email address in this method by sending it to an external API. You can use the external service like Email-Verification API.
Example:
<form id="emailForm">
<input type="text" id="email" placeholder="Enter your email">
<button type="submit">Submit</button>
<p id="errorMessage" style="color: red; display: none;">Please enter a valid email address.</p>
</form>
<script>
document.getElementById('emailForm').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent form submission
const email = document.getElementById('email').value;
// Example API call
const apiUrl = ‘’ \\ Add API URL of your choice
fetch(apiUrl)
.then(response => response.json())
.then(data => {
if (data.isValid) {
alert('Valid email address!');
} else {
document.getElementById('errorMessage').style.display = 'block';
}
})
.catch(error => {
console.error('Error validating email:', error);
});
});
</script>
Conclusion
You can use JavaScript libraries and regular expressions to validate emails. This improves security and makes sure users provide correct email addresses. The methods listed above are more efficient in validating email addresses.
FAQs
1. What is a regular expression (regex)?
It is the sequence of characters that defines the search pattern. It is often used for string matching or validation.
2. Is there any alternative method to validate email addresses in JavaScript?
Yes, you can use libraries like validator.js which provide built-in functions for email validation.
3. Why use regex for email validation?
Regex is a powerful and ideal tool for checking whether a string matches a specific pattern.