DEV Community

Cover image for Lean on the web platform to validate emails
abdellah ht
abdellah ht

Posted on

Lean on the web platform to validate emails

Email validation in javascript is a very common topic in the web development world.

The first instinct is to match a string against a Regex, but the Regex can get hairy really fast as it tries to accommodate the whole standard specification for email addresses.

Just take a look at this accepted response on stackoverflow:

const emailRegex =
const isValild = emailRegex.test(someEmail);
Enter fullscreen mode Exit fullscreen mode

That works but nobody knows why!

The browser has built in form validation for different types of for inputs.

An input with a specified type, in this case type="email", is only valid if it has a valid email address.

This method offloads the validation burden to the browser and surfaces a nice API where the validation question is answered with a simple input.checkValidity().


function validateEmailHTML(email = "") {
    // create an offscreen input element 
    let input = document.createElement("input");
    // give it the "email" type constraint πŸ’Œ
    input.type = "email";
    // fill it ✍️
    input.value = email;
    // profit πŸŽ‰
    return input.checkValidity();
Enter fullscreen mode Exit fullscreen mode

Thanks for your attention!


Top comments (0)