Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created April 26, 2020 19:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m3g4p0p/4492e6d4c730d7c3be813c145746ba1b to your computer and use it in GitHub Desktop.
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
/**
* 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
@m3g4p0p
Copy link
Author

m3g4p0p commented Apr 26, 2020

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:

const input = document.createElement('input')

input.type = 'email'

export const validateEmail = value => {
  input.value = value
  return input.validity.valid
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment