Created
April 26, 2020 19:30
-
-
Save m3g4p0p/4492e6d4c730d7c3be813c145746ba1b to your computer and use it in GitHub Desktop.
Test if a string is a valid email address using the constraint validation API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Test if a string is a valid email address | |
* using the constraint validation API, rather | |
* than unwieldy regular expressions | |
* | |
* @param {string} value | |
* @returns {boolean} | |
*/ | |
const validateEmail = value => Object.assign( | |
document.createElement('input'), | |
{ type: 'email', value } | |
).validity.valid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
EZ Email Validation
Testing if a string is a valid email address is notoriously difficult -- see this classic SO thread for some impressions. However, in a browser context we can harness the constraint validation API for an easier and more robust solution; the idea is setting the value of an
<input type="email">
element and let the internals do the heavy lifting.Of course, IRL one might reuse the same
input
element when doing multiple checks, rather than creating a new intermediate one on the fly; the above code is just meant to fit into one LOC (if you wanted to) for illustration purposes. For example, as an ES module: