In HTML5, you can use built-in form validation to check an email address. This works by setting the
type="email" attribute on an
input element. You might need to check an email address programatically, though, so here are a few ways you can do that in vanilla JS.
Your first option is to use a regular expression.
Email inputs use the following regular expression under the hood:
Source: 220.127.116.11.5 E-mail state (
type=email) in the HTML Standard.
We can combine this with the
RegExp.prototype.test() method to create a helper function:
You can use it by passing in the email input’s
Constraint Validation API
You can also use the Constraint Validation API.
Assume you have an
input element with its
type attribute set to
You can use its
validity property to get a
ValidityState object. Then you can check the
typeMismatch property of that object.
As explained in the MDN Web Docs, the
typeMismatch property is:
trueif the value is not in the required syntax (when
falseif the syntax is correct.
Therefore, we can create a helper function like so. Notice that I’m using the logical NOT (
!) operator, because the property is
true if the value is NOT in the required syntax:
We use this helper function by passing in the
input element itself. Notice that I pass in
emailInput and not
RegExp.prototype.test() method is supported back to IE6.
ValidityState.typeMismatch property is supported back to IE10.
For more information, check out the compatibility data on Can I Use:
- HTMLInputElement API: validity
Bouncer: a lightweight plugin
If you want a simple plugin, my friend Chris Ferdinandi maintains Bouncer:
a lightweight form validation script that augments native HTML5 form validation elements and attributes.
All you have to do is add standard validation attributes to your form, initialize the script, and away you go.
In vanilla JS, you can use a regular expression or the Constraint Validation API to check an email address. You can also use Bouncer, a lightweight form validation script my friend Chris Ferdinandi maintains.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!