Validating email addresses is key to ensuring data quality and successful user sign-ups. We'll explore five ways to handle this in jQuery, providing working code for each. You'll also see the common pitfalls of these methods and how Abstract API offers a more robust solution.
How to Implement Email Validation in jQuery
Here are four common methods to validate email addresses with jQuery. Each technique approaches the problem differently, from simple pattern matches to more complex server-side checks.
Direct Regex in a jQuery Handler
This approach attaches an event handler, like `blur` or `submit`, to a form element. When the event fires, it tests the input value against a regular expression. The regex pattern attempts to match the standard format of an email address. If the test fails, the code can prevent form submission or show an alert.
const emailRx = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('form').on('submit', e => {
const v = $('#email').val();
if (!emailRx.test(v)) { e.preventDefault(); alert('Bad address'); }
});
HTML5 Input Type and the DOM Validity API
This method relies on the browser's native validation for inputs with `type="email"`. jQuery hooks into the `invalid` and `input` events. The `invalid` event fires when the value is not a valid email, which allows you to add an error class. The `input` event lets you remove the error class once the user corrects the entry.
$('#email')
.attr('type', 'email') // modern browsers validate automatically
.on('invalid', function () { $(this).addClass('error'); })
.on('input', function () {
if (this.checkValidity()) $(this).removeClass('error');
});
The jQuery-Validation Plugin
A popular choice is the jQuery-validation plugin, which includes a pre-built email validation rule. You initialize the plugin on your form with the `validate` method. Inside, you specify rules for each field, such as `required: true` and `email: true`. The plugin handles the validation logic and displays custom error messages you define.
$('#myForm').validate({
rules: { email: { required: true, email: true } },
messages:{ email: 'Please supply a valid address.' }
});
Remote AJAX Validation
This technique uses the jQuery-validation plugin's `remote` rule to perform an asynchronous check. When the user enters an email, the plugin sends an AJAX request to a server-side script you specify. The script validates the email and must return a simple true or false response. The plugin then marks the field as valid or invalid based on this server response.
$('#myForm').validate({
rules: {
email: {
required: true,
email: true,
remote: { url: '/check-email.php', type: 'post' }
}
}
});
Challenges of jQuery Email Validation
While these client-side methods offer quick feedback, they share fundamental limitations that can compromise data quality. These approaches often fail to account for the full complexity of modern email standards.
- Regex patterns, used in direct handlers and the validation plugin, cannot parse all valid formats. They often reject compliant addresses with quoted parts or IP-literal hosts, which makes them unreliable and difficult to maintain.
- Client-side scripts cannot query DNS records to confirm a domain's mail servers. Methods like direct regex or the HTML5 input type only check syntax, not actual deliverability, and require constant updates for new TLDs.
- Internationalized addresses with non-ASCII characters expose browser inconsistencies. The HTML5 email input type and common regex patterns often reject valid Unicode local parts or domains, which frustrates international users.
- Common email conventions like plus-addressing or internal domains without a TLD often cause validation failures. Regex-based approaches force a choice between leaky validation or a patchwork of complex exceptions to handle these cases.
Validate Emails with Abstract API
Implement effective email validation in your jQuery project to ensure you only collect valid emails.
Get started for free
How Abstract API Handles Email Validation in jQuery
Abstract API addresses the core weaknesses of traditional methods. It replaces a brittle regex pass with a single, comprehensive HTTP call.
- Replaces unreliable regex with `deliverability` and `is_valid_format` flags to confirm syntax.
- Checks for mailbox existence with `is_mx_found` and `is_smtp_valid` booleans.
- Detects disposable or risky domains through `disposable`, `free_email`, and `role` flags.
- Offers a `quality_score` from 0.01 to 0.99 for quick decisions.
- Provides user feedback with an `auto_correct` feature that suggests fixes for common typos.
How to Add Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, the addition of its email validation API to your project is simple.
- Sign up at Abstract API and get your Email Validation API key.
- Add jQuery to your page if it is not already present.
- Create an input field with the id
inputemail
and a submit button with the id submitBtn
. - Load a script that executes on a button click, reads the input value, and calls the API endpoint.
- Parse the JSON response within the success callback and control form submission based on the
deliverability
and quality_score
fields. - Show errors or autocorrect suggestions in the UI, or persist the clean email for downstream use.
$(document).ready(function () {
$('#submitBtn').on('click', function (e) {
e.preventDefault();
const email = $('#inputemail').val();
$.getJSON(
`https://emailvalidation.abstractapi.com/v1/?api_key=YOUR_KEY&email=${encodeURIComponent(email)}`,
function (data) {
if (data.deliverability === 'DELIVERABLE' &&
data.is_smtp_valid.value &&
data.quality_score > 0.90) {
console.log('Good email:', data.email);
// proceed with form submit or AJAX
} else {
const suggestion = data.auto_correct || 'not deliverable';
alert(`Please fix your email (${suggestion}).`);
}
}
);
});
});
Sample Email Validation Implementation with Abstract API
This jQuery code snippet captures the email address a user enters into a form. It sends the address to Abstract API for validation. The script then evaluates the API's JSON response to decide if the form submission should proceed.
If the API confirms the email is deliverable with a high quality score, the form can submit. Otherwise, it alerts the user with a suggested correction or a simple error message. This check happens before the form data reaches your server.
Below is a sample API response for an invalid email.
{
"email": "john.smith@gmial.com",
"auto_correct": "john.smith@gmail.com",
"deliverability": "UNDELIVERABLE",
"quality_score": 0.11,
"is_valid_format": { "value": true, "text": "Valid format" },
"is_mx_found": { "value": false, "text": "No MX records" },
"is_smtp_valid": { "value": false, "text": "Mailbox not found" }
}
In this example, the API recognizes the typo in "gmial.com". While the format is valid, the API flags the email as UNDELIVERABLE
because the domain has no MX records and the SMTP check failed. It provides an auto_correct
suggestion and a low quality_score
, which lets the front-end prompt the user for a fix.
Final Thoughts
Traditional regex validation often fails because it cannot confirm mailbox existence or detect risky domains. Abstract API overcomes these limits with a single API call that performs deep checks, from SMTP handshakes to typo correction. For reliable user email validation, consider a free account with Abstract API to get your API key.
Validate Emails with Abstract API
Ensure clean data and improve user sign-ups by implementing proper email validation in jQuery.
Get started for free