Validating email inputs is a common requirement for web forms. We'll explore five ways to handle email validation in Bootstrap, complete with working code examples. We will also look at the common pitfalls of these traditional approaches and see how Abstract API provides a more robust solution.
How to Implement Email Validation in Bootstrap
Bootstrap offers several ways to validate email fields. Here we explore four common methods, from simple HTML5 attributes to custom JavaScript and server-side checks, each with code examples.
HTML5 Constraint Validation with a Bootstrap Wrapper
This approach uses the browser's native validation for inputs with `type="email"`. Bootstrap does not add its own validation logic. It simply applies visual styles to the input based on the browser's `:valid` and `:invalid` states.
The JavaScript code finds all forms that need validation and listens for a submit event. When a user submits the form, `checkValidity()` runs. If the form is invalid, the submission stops. The `was-validated` class is then added, which makes Bootstrap's validation feedback appear.
<form class="needs-validation" novalidate>
<input type="email" class="form-control" id="workEmail" required>
<div class="invalid-feedback">Bad address</div>
</form>
<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 .is-valid and .is-invalid Classes
For custom validation rules, like the rejection of specific domains, you can use a regular expression. This method bypasses the browser's built-in validator. You define a regex pattern and test the input value against it.
The code attaches an event listener that fires on every keystroke and checks if the input matches the regex. Based on the result, it adds or removes Bootstrap's `is-valid` and `is-invalid` classes. This approach directly controls visual feedback without the `was-validated` class or `novalidate` attribute. The styling is consistent with Bootstrap's server-side validation examples.
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)
})
The jQuery Validation Plugin with Bootstrap
This method integrates the popular jQuery Validation plugin with Bootstrap's styling. The plugin itself handles complex validation logic, like RFC-5322 compliance. You configure the plugin to use Bootstrap's classes for the display of validation states.
The `rules` object defines what makes an input valid. The `highlight` and `unhighlight` functions add or remove the `is-invalid` and `is-valid` classes. `errorPlacement` tells the plugin to wrap error messages to match Bootstrap's design.
$('#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 Validation with a Server
Some validation, like checks for uniqueness or MX records, must happen on a server. This method uses an asynchronous `fetch` call to an API endpoint where the validation logic runs.
The code attaches an event listener to the input field's `blur` event. This triggers a function that sends the email to the server. After the server responds, the function toggles the `is-valid` and `is-invalid` classes based on the answer.
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 Traditional Approaches
These methods appear straightforward but introduce significant issues with reliability, maintenance, and user experience. The validation they provide is often superficial and creates a false sense of security.
- The HTML5 constraint validation method depends on inconsistent browser implementations. It allows trivial addresses like a@b and fails to handle internationalized domains, so behavior varies widely across different user environments.
- Custom JavaScript regex patterns become unmaintainable. A pattern that enforces RFC 5322 is enormous, and simpler versions can cause performance problems or break on certain inputs, a major drawback for this method.
- Client-side syntax checks cannot confirm if a domain has MX records or if an address is from a disposable provider. This limitation gives a false sense of email deliverability assurance.
- The jQuery Validation plugin adds a heavy dependency, while asynchronous server checks introduce latency. Both approaches often require developers to duplicate validation logic on the client and the server for a good user experience.
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. It moves beyond simple syntax checks to confirm actual email deliverability.
- It performs validation on the server, so users cannot bypass the check.
- The API conducts real-time MX lookups and SMTP handshakes to verify server health.
- It screens for disposable, free, or role-based addresses and suggests corrections for common typos.
- The system returns a clear deliverability verdict plus granular flags for detailed risk scores.
How to Set Up Abstract API in Your Project
Once you understand Abstract’s capabilities, you can add its email validation API to your project with ease. The process requires just a few steps to get your development environment ready.
- First, sign in at Abstract API, create a new project, and copy your unique Email Validation API key.
- Next, add an environment variable named ABSTRACT_EMAIL_KEY and set its value to your key. You should never hard-code API keys directly in your code.
- Install a client like Axios with the command npm i axios, or you can use the native fetch API.
- Finally, deploy your project and monitor API usage and logs from your Abstract dashboard.
Sample Email Validation Implementation with Abstract API
The sample code below shows a standard Bootstrap form with a JavaScript listener that intercepts the submit event. Instead of a direct submission, the script sends the user's email address to Abstract API for validation.
If the API returns a DELIVERABLE status and confirms the address is not disposable, the script allows the form submission. Otherwise, it adds an invalid class to the input field to show an error to the user.
<form id="reg" class="needs-validation">
<input type="email" id="email" class="form-control" required>
<button class="btn btn-primary">Sign Up</button>
</form>
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 input like "user@gnamil.com", the API returns a detailed JSON object. This response shows the address is undeliverable because the SMTP probe failed, even though the format is valid.
The API also provides a helpful auto-correct suggestion, "user@gmail.com", and other data points you can use to build more complex logic.
{
"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
}
Final Thoughts
Traditional email validation methods often fall short. They only check syntax, not actual deliverability, which allows bad addresses to pollute your data. Abstract API solves this problem with server-side verification that includes real-time SMTP and MX record checks.
To reliably validate user emails, consider an account on Abstract API and 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