function isValidEmail(email) {
return email.includes('@');
}
Join us
@idjuric660 ・ May 04,2024 ・ 13 min read ・ 403 views ・ Originally posted on mailtrap.io
In web development, email validation in JavaScript rules the game. Be it form validation, or a sign-up sequence email validation, you need to be sure users type the right thing.
Here, I cover JavaScript email validation front-end and back-end (server-side). And this “full-stack” tutorial is geared towards beginners, but there are also nuggets of wisdom for more advanced users.
As always, there are JavaScript code snippets you can easily copy-paste to your project.
Email validation serves multiple purposes:
Plus, an incorrectly formatted email address can lead to failed communication, resulting in a poor user experience and potential loss of users or customers.
In this section, I’ll cover a basic validation step – checking for the presence of the ‘@’ symbol. See the function below:
function isValidEmail(email) {
return email.includes('@');
}
The isValidEmail
function takes a single argument email
and uses the includes
method to check if the @
symbol is present. It returns true
if the symbol is found, indicating a potentially valid email address, and false
otherwise.
Of course, the method has its limitations due to its simplicity. But there’s a silver lining, understanding the limitations helps set the scene for more complex validation methods in the following sections. Here’s what the limitations are:
Tip: You can apply the basic validation as the first step, but don’t rely solely on it.
Regular expressions (regex) are tools for pattern matching and text manipulation.
They enable you to define a search pattern that can be used to perform various text operations such as search, replace, and validation. Here’s a simple example of a regex:A-za-z0-9
a-za-z
section matches any letter from A to Z (uppercase and lowercase)0-9
section matches digits from 0 to 9Note that the above is just for shows, you need a more complex regex for email validation.
To catch an invalid email address, a regex can be designed to match the general structure of an address, ensuring it conforms to standard email formatting rules.
A widely accepted pattern that adheres to most email validation standards is as follows:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
It covers:
Here’s how you can use the above regex pattern within a JavaScript function to validate email addresses:
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
The validateEmail
function takes an email address as input and returns true
if the email matches the regex pattern, indicating a valid email format, or false
otherwise.
As said, regex isn’t bulletproof, unless you make it a mile-long, attempting to cover all edge cases. So, check what to keep in mind:
How to avoid the pitfalls?
Tip: regexp
can be used to define more specialized filters, note that it’s not common in email validation.
Email validation within an HTML form helps ensure data integrity and enhances user experience.
Real-time feedback within modern web apps guides users to correct errors immediately, rather than after form submission. It helps avoid user frustration that might lead to form abandonment.
This immediate feedback implementation can be achieved by listening to user input events and validating them on the fly.
I’ll be using the oninput
or onchange
HTML event attributes trigger real-time email validation functions.
oninput
event triggers every time the user types or deletes something in the input field, providing immediate feedback. onchange
event triggers after the element loses focus, which is useful for final validation before submission. In this JavaScript tutorial, I’ll use the oninput
event trigger and integrate regex-based validation. It’s a simple doctype html registration form without form name, textarea
, CSS styles, div
class, li
class, etc. Nonetheless, if you add them the address validation logic is still the same.
Check the steps below:
<form id="registrationForm">
<label for="emailInput">Email:</label>
<input type="email" id="emailInput" oninput="validateEmailInput()">
<span id="emailFeedback" style="color: red;"></span>
</form>
2. Implement the validateEmailInput
function that uses the regex pattern for email validation:
function validateEmailInput() {
const emailInput = document.getElementById('emailInput').value;
const feedbackElement = document.getElementById('emailFeedback');
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailRegex.test(emailInput)) {
feedbackElement.textContent = ""; // Email is valid
} else {
feedbackElement.textContent = "Please enter a valid email address.";
}
}
Pro Tips:
If you’re interested in a full HTML5 email validation tutorial, check the linked article.
jQuery is a fast, small, and feature-rich JavaScript library, and it can help a lot with the following:
Also, it has one of the easiest-to-use APIs that work across different browsers.
But, in the context of validation, jQuery’s greatest strength is the ability to abstract complex tasks into methods that can be called with just a few lines of code.
To put it plainly, it simplifies selecting and manipulating elements and attaching event listeners. In turn, it’s a great choice for email validation within web apps, so here’s how to use it.
<form id="registrationForm">
<label for="emailInput">Email:</label>
<input type="email" id="emailInput">
<span id="emailFeedback" style="color: red;"></span>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
2. Use jQuery to select the input field and bind an input event to perform validation
$(document).ready(function() {
$('#emailInput').on('input', function() {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailRegex.test($(this).val())) {
$('#emailFeedback').text(''); // Email is valid
} else {
$('#emailFeedback').text('Please enter a valid email address.');
}
});
});
validator
’ for email validationvalidator
is a lightweight JavaScript library that offers a range of string validation and sanitazation functions. It is designed to be simple, efficient, and flexible, making it an excellent tool for various validation scenarios, including email validation.
For me, the main highlights include:
validator
can be used in both browser and Node.js environments, ensuring versatility in deployment.With all the goodies listed, I’ll now show you how to implement it.
validator
in your project. If you’re working in a browser environment, you can add it directly with a script tag. <script src="https://unpkg.com/validator@latest/validator.min.js"></script>
2. Define the validation rules and the custom error message for email validation.
const form = document.getElementById('registrationForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
const email = form.elements.email.value;
let errorMessages = [];
// Email validation
if (!validator.isEmail(email)) { // Checks if the email is in a valid format
errorMessages.push('Invalid email format.');
}
// Display error messages or submit the form
if (errorMessages.length > 0) {
const errorMessage = errorMessages.join(', ');
document.getElementById('emailFeedback').textContent = errorMessage;
} else {
// No errors, proceed with form submission or further processing
document.getElementById('emailFeedback').textContent = '';
// form.submit(); Uncomment this line if you wish to submit the form upon validation
}
});
3. As always, you’ll need an HTML form with an input field for the email and a place to display the validation error message:
<form id="registrationForm">
<label for="emailInput">Email:</label>
<input type="email" name="email" id="emailInput">
<span id="emailFeedback" style="color: red;"></span>
<button type="submit">Submit</button>
</form>
Server-side validation acts as the final checkpoint before data is processed or stored. It offers a layer of protection against invalid or malicious data that might bypass client-side checks.
To that, Ajax (Asynchronous JavaScript and XML) allows web pages to be updated asynchronously by exchanging data with a web server in the background. It means you can validate form data on the server without reloading the web page, offering a seamless experience to the users.
Here’s how to implement it:
function validateEmailServerSide(email) {
fetch('/validate-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: email })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.isValid) {
alert('Email is valid!');
} else {
alert('Email is invalid!');
}
})
.catch(error => {
console.error('There was a problem with your fetch operation:', error);
});
}
This function sends the email to a server endpoint (/validate-email
) via a POST request and processes the response.
2. On the server side, you can set up a simple Node.js server using Express to handle the validation request.
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// Route to handle email validation
app.post('/validate-email', (req, res) => {
const { email } = req.body;
// Simple regex for demonstration purposes
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isValid = emailRegex.test(email);
// In a real scenario, you might check against a database here
res.send({ isValid });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Pro Tips:
For starters, I’d like to point out the difference between email validation and email verification.
Several services offer API-based email verification, and popular examples include Hunter, ZeroBounce, and NeverBounce.
Of course, these platforms provide detailed documentation on how to integrate their APIs into your applications.
And here, I’ll show you how to verify email address using Hunter.io API. For this exemplary integration, I’m using fetch
, which should work regardless of your chosen service.
function verifyEmail(email) {
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const url = `https://api.hunter.io/v2/email-verifier?email=${email}&apiKey=${apiKey}`;
fetch(url)
.then(response => response.json())
.then(({data}) => {
if (data.status === 'valid') {
console.log('Email is verified and active.');
} else {
console.log('Email cannot be verified.');
}
})
.catch(error => {
console.error('Error verifying email:', error);
});
}
Some tips on applying email verification:
Further reading on email validation:
Important Note on using Hunter API:
Hunter.io API email verification response doesn’t directly return ‘isVerified’ field. It actually provides a data object with various email verification details.
You can do the following to destructure the data object and get the status:
.then(response => response.json())
.then(({data}) => {
if (data.status === 'valid') {
console.log('Email is verified and active.');
} else {
console.log('Email cannot be verified.');
}
})
While email validation focuses on confirming the correctness and existence of an email address, it’s just the beginning of a comprehensive email testing strategy. Here’s the spectrum of email testing to consider:
Mailtrap Email Delivery Platform, with its Email Testing feature, allows you to check all of the above without spamming your recipients. It’s a sandbox where developers test and debug email functionality via a fake SMTP server.
Mailtrap Email Testing captures emails sent from your development or staging environment into a safe space to conduct comprehensive email testing. It’s also easy to integrate and we provide read-made snippets in 20+ languages (PHP, Python, C#, etc.)
And you can do the following:
But as an Email Delivery Platform, we also offer Email Sending via SMTP or API. For instance, you can easily integrate it with your web or contact form and enjoy high deliverability rates by design.
If you want to know how to do contact form email validation, check out our video tutorial.
Article by Yevhenii Odyntsov, Content @Mailtrap
We appreciate the you chose this article to find out how to do email validation with JavaScript. If you want to find more interesting content on related topics, follow Mailtrap blog!
Join other developers and claim your FAUN account now!
Technical Content Writer, Mailtrap
@idjuric660Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.