In today's digital age, collecting email addresses is a crucial part of any marketing strategy. However, ensuring the correctness of these email addresses is equally important. Incorrect or fake email addresses can lead to high bounce rates, low engagement, and poor deliverability of your email campaigns. Implementing email verification in your web forms can help mitigate these issues. In this blog post, we'll walk through how to organically verify email addresses using HTML and JavaScript.
Email verification is the process of ensuring that an email address is valid and deliverable. There are multiple layers to email verification, ranging from basic syntax checks to complex DNS lookups and SMTP verifications. In this guide, we'll focus on the foundational aspects of client-side validation using HTML and JavaScript.
Client-side validation occurs before the data is submitted to the server. It helps to catch common errors and provide immediate feedback to users, enhancing their experience and improving the quality of data collected.
First, we need a basic HTML form where users can input their email addresses. This will be our starting point:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Verification</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="form-container">
<form id="email-form">
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email" required>
<div id="email-feedback"></div>
<button type="submit">Submit</button>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
This simple form includes a label, an input field for the email address, a feedback div where we can display validation messages, and a submit button.
Client-side validation can be achieved using JavaScript. We'll add an event listener for form submission and use JavaScript functions to validate the email input.
Add the following JavaScript code in script.js
:
document.addEventListener('DOMContentLoaded', () => {
const emailForm = document.getElementById('email-form');
const emailInput = document.getElementById('email');
const emailFeedback = document.getElementById('email-feedback');
emailForm.addEventListener('submit', function(event) {
event.preventDefault();
const email = emailInput.value;
if (validateEmail(email)) {
emailFeedback.textContent = 'Valid email address!';
emailFeedback.style.color = 'green';
} else {
emailFeedback.textContent = 'Invalid email address. Please enter a valid email.';
emailFeedback.style.color = 'red';
}
});
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
});
In this script:
event.preventDefault()
.Regular expressions (regex) are patterns used to match character combinations in strings. For email validation, a common regex pattern is used to ensure the email has a valid structure.
Below is a breakdown of the regex pattern we'll use:
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
^[^\s@]+
: Asserts that the match starts with one or more characters that are not whitespaces or '@' symbols.@[^\s@]+
: The '@' symbol followed by one or more characters that are not whitespaces or '@' symbols.\.[^\s@]+$
: A literal '.' followed by one or more characters that are not whitespaces or '@' symbols, and asserts that the match ends there.This regex pattern is effective for basic email structure validation but may not catch all edge cases. Therefore, advanced validation techniques may still be necessary.
User experience can be significantly improved by providing real-time feedback as users type their email addresses. We can achieve this by adding an event listener to the email input field.
Update your script.js
to include real-time validation:
document.addEventListener('DOMContentLoaded', () => {
const emailForm = document.getElementById('email-form');
const emailInput = document.getElementById('email');
const emailFeedback = document.getElementById('email-feedback');
emailInput.addEventListener('input', function() {
const email = emailInput.value;
if (validateEmail(email)) {
emailFeedback.textContent = 'Valid email address!';
emailFeedback.style.color = 'green';
} else {
emailFeedback.textContent = 'Invalid email address. Please enter a valid email.';
emailFeedback.style.color = 'red';
}
});
emailForm.addEventListener('submit', function(event) {
event.preventDefault();
const email = emailInput.value;
if (validateEmail(email)) {
emailFeedback.textContent = 'Submission successful!';
emailFeedback.style.color = 'green';
} else {
emailFeedback.textContent = 'Invalid email address. Please enter a valid email.';
emailFeedback.style.color = 'red';
}
});
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
});
With this update:
validateEmail
function is now called every time the user types in the email input field.While client-side validation greatly enhances user experience, it is not foolproof. Advanced validation, including MX record checks and SMTP validation, can be performed with the help of external APIs. Several services provide email validation APIs, such as Hunter.io, ZeroBounce, and NeverBounce.
For demonstration, let's integrate an email validation API. We'll use a mock API endpoint and showcase how you might structure the asynchronous validation request.
Add the following code to your script.js
:
async function validateEmailWithAPI(email) {
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const apiUrl = `https://api.example.com/verify?email=${email}&apikey=${apiKey}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
if (data.isValid) {
return true;
} else {
return false;
}
} catch (error) {
console.error('Error fetching email validation:', error);
return false;
}
}
// Integrate with existing validation logic
document.addEventListener('DOMContentLoaded', () => {
const emailForm = document.getElementById('email-form');
const emailInput = document.getElementById('email');
const emailFeedback = document.getElementById('email-feedback');
emailInput.addEventListener('input', async function() {
const email = emailInput.value;
if (validateEmail(email)) {
emailFeedback.textContent = 'Validating...';
emailFeedback.style.color = 'orange';
const isValid = await validateEmailWithAPI(email);
if (isValid) {
emailFeedback.textContent = 'Valid email address!';
emailFeedback.style.color = 'green';
} else {
emailFeedback.textContent = 'Invalid email address.';
emailFeedback.style.color = 'red';
}
} else {
emailFeedback.textContent = 'Invalid email format.';
emailFeedback.style.color = 'red';
}
});
emailForm.addEventListener('submit', async function(event) {
event.preventDefault();
const email = emailInput.value;
if (validateEmail(email)) {
emailFeedback.textContent = 'Validating...';
emailFeedback.style.color = 'orange';
const isValid = await validateEmailWithAPI(email);
if (isValid) {
emailFeedback.textContent = 'Submission successful!';
emailFeedback.style.color = 'green';
} else {
emailFeedback.textContent = 'Invalid email address.';
emailFeedback.style.color = 'red';
}
} else {
emailFeedback.textContent = 'Invalid email format.';
emailFeedback.style.color = 'red';
}
});
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
});
In this integration:
validateEmailWithAPI
function performs an asynchronous fetch request to an external API.Remember to replace YOUR_API_KEY
and https://api.example.com/verify
with your actual API key and API endpoint.
Email validation is an essential component of any web form, ensuring that collected email addresses are valid and deliverable. Using HTML and JavaScript, we can implement basic client-side validation to catch common errors and provide immediate feedback to users.
For more advanced validation, integrating with external APIs can help verify the deliverability of email addresses, providing an extra layer of assurance. By following the steps outlined in this tutorial, you can enhance the quality of your email lists and improve the success rate of your email marketing campaigns.
Implement these techniques to not only improve user experience but also to strengthen your data collection process. Happy coding!