Lean on the web platform to validate emails

_hariti

abdellah ht

Posted on October 15, 2022

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 =
        /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
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().

Example:

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!

:wq

πŸ’– πŸ’ͺ πŸ™… 🚩
_hariti
abdellah ht

Posted on October 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related