Lean on the web platform to validate emails
abdellah ht
Posted on October 15, 2022
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);
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();
}
Thanks for your attention!
:wq
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
November 11, 2024