Proper email validation is a key part of any Bootstrap form. Here, we'll walk through five different methods for adding it, providing code snippets for each. We'll then examine the drawbacks of these traditional techniques and show how Abstract API addresses them.
How to Implement Email Validation in Bootstrap
Bootstrap offers several ways to validate email inputs. These methods range from simple HTML5 attributes to custom JavaScript logic, each one integrates with Bootstrap’s visual feedback system.
HTML5 Constraint Validation with a Bootstrap Wrapper
This technique uses the browser’s native validation for inputs with a "type" of "email". Bootstrap does not add new logic but applies its own styles over the browser's ":valid" and ":invalid" states.
The JavaScript targets forms with the "needs-validation" class. When a user attempts to submit the form, the script prevents submission if the `checkValidity()` method returns false and adds the "was-validated" class. This action makes Bootstrap’s validation styles visible.
<!-- Markup -->
<form class="needs-validation" novalidate>
<input type="email" class="form-control" id="workEmail" required>
<div class="invalid-feedback">Bad address</div>
</form>
<!-- JS -->
<script>
document.querySelectorAll('.needs-validation')
.forEach(f => f.addEventListener('submit', e => {
if (!f.checkValidity()) e.preventDefault();
f.classList.add('was-validated');
}));
</script>
Pure JavaScript Regex with Bootstrap Classes
For custom validation rules, like a rule to disallow certain domains, you can use JavaScript's regular expressions. This approach bypasses the browser's built-in validator and gives you full control over the logic.
An event listener on the input field tests the value against a regex pattern with each keystroke. It then programmatically toggles Bootstrap’s "is-valid" or "is-invalid" classes on the element to show immediate feedback, as documented for server-side validation.
const rx = /^[A-Za-z0-9._%+-]+@(?!gmail\.com)([A-Za-z0-9-]+\.)+[A-Za-z]{2,}$/;
const el = document.getElementById('personalEmail');
el.addEventListener('input', () => {
const ok = rx.test(el.value);
el.classList.toggle('is-valid', ok);
el.classList.toggle('is-invalid', !ok);
});
jQuery Validation Plugin Integration
The jQuery Validation plugin can manage complex validation rules while you retain Bootstrap's visual language. The plugin understands the difference between HTML5 standards and stricter RFC-5322 email formats.
You configure the plugin to use Bootstrap's classes. The "highlight" and "unhighlight" options add or remove "is-valid" and "is-invalid". The "errorPlacement" function ensures error messages appear correctly within Bootstrap's feedback containers.
$('#acctForm').validate({
rules: { email: { required: true, email: true } },
highlight: el => $(el).addClass('is-invalid').removeClass('is-valid'),
unhighlight: el => $(el).addClass('is-valid').removeClass('is-invalid'),
errorPlacement: (err, el) => err.addClass('invalid-feedback').insertAfter(el)
});
Asynchronous Server-Side Validation
When validation requires a backend check, such as for email uniqueness or MX record existence, an asynchronous call is necessary. This is often tied to the input field’s "blur" event to avoid excessive requests.
The script sends the email value to a server endpoint with `fetch()`. After it receives a response, it toggles the "is-valid" or "is-invalid" class on the input field, which again uses Bootstrap’s standard presentation layer for feedback.
async function verify(value) {
const r = await fetch('/api/verify-email?e=' + encodeURIComponent(value));
return (await r.json()).ok;
}
email.addEventListener('blur', async () => {
const ok = await verify(email.value);
email.classList.toggle('is-valid', ok);
email.classList.toggle('is-invalid', !ok);
});
Challenges of Email Validation in Bootstrap
While these methods integrate with Bootstrap's styles, they present significant practical challenges. The validation is often superficial, inconsistent across browsers, and difficult to maintain as standards evolve.
- The HTML5 constraint validation method depends on inconsistent browser implementations. The built-in checks are often too permissive, accept invalid formats, and produce different error messages and behaviors across browsers, which creates an unreliable user experience.
- Custom JavaScript regex patterns become difficult to maintain. A pattern that enforces strict RFC compliance is complex and can degrade performance, while simpler versions often fail to account for new top-level or internationalized domains.
- Client-side checks, whether with HTML5 or regex, cannot confirm an email's deliverability. They do not verify domain existence, MX records, or disposable addresses. This limitation provides a false sense of security about the email's validity.
- The jQuery Validation plugin adds a significant dependency to modern projects. It also requires custom code for asynchronous checks, which complicates the implementation for tasks like server-side verification of an email address.
Validate Emails with Abstract API
Start validating emails today to improve data quality and prevent bounces from hurting your reputation.
Get started for free
How Abstract API Handles Email Validation in Bootstrap
Abstract API addresses the core weaknesses of traditional methods through server-side checks that assess an email's actual deliverability.
- It moves validation to the server, so users cannot bypass the check.
- It performs real-time MX record lookups and SMTP handshakes to confirm server health.
- It screens for disposable, free, and role-based email providers.
- It provides typo auto-correction and a continuously trained quality score to handle edge cases.
- It returns a clear deliverability verdict and granular flags for detailed risk scores.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, you can add its email validation API to your project with ease.
- Sign in at Abstract API, create a project, and copy your Email Validation API key.
- Set an environment variable for your key, such as ABSTRACT_EMAIL_KEY=your_key.
- Install a client like Axios through the command "npm i axios" or use native fetch.
- Create your Bootstrap form and connect it to your script, as the example below shows.
- Deploy the application and monitor its performance through the Abstract dashboard.
<form id="reg" class="needs-validation">
<input type="email" id="email" class="form-control" required>
<button class="btn btn-primary">Sign Up</button>
</form>
Sample Email Validation Implementation with Abstract API
The JavaScript code below attaches an event listener to the form. When a user submits the form, the code prevents the default submission. It then sends the email address to the Abstract API endpoint for validation. If the API returns a "DELIVERABLE" status and the email is not from a disposable provider, the form proceeds. Otherwise, it marks the input field as invalid.
document.getElementById('reg').addEventListener('submit', async e => {
e.preventDefault();
const email = document.getElementById('email').value;
const { data } = await axios.get(
'https://emailvalidation.abstractapi.com/v1/',
{ params: { api_key: process.env.ABSTRACT_EMAIL_KEY, email } }
);
if (data.deliverability === 'DELIVERABLE' && !data.is_disposable_email) {
e.target.submit();
} else {
document.getElementById('email').classList.add('is-invalid');
}
});
For an address like "user@gnamil.com", the API returns a detailed JSON response. It might look like this:
{
"email": "user@gnamil.com",
"auto_correct": "user@gmail.com",
"deliverability": "UNDELIVERABLE",
"quality_score": 0.18,
"is_valid_format": true,
"is_free_email": true,
"is_disposable_email": false,
"is_role_email": false,
"is_catchall_email": false,
"is_mx_found": true,
"is_smtp_valid": false
}
In this example, the address format is correct, but the SMTP probe failed, so the final verdict is "UNDELIVERABLE". The API also suggests a correction to "user@gmail.com" and provides other flags. You can use these details to prompt the user for a correction, reject the submission, or flag it for manual review.
Final Thoughts
Traditional email validation in Bootstrap often just checks syntax and can be bypassed. This allows bad addresses to harm your sender reputation. Abstract API performs server-side checks for actual deliverability, which includes MX record lookups and SMTP handshakes. To reliably validate user emails, consider an account on Abstract API to get your free API key.
Validate Emails with Abstract API
Protect your data integrity and stop bad signups by adding email validation to your forms.
Get started for free