Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 7, 2021 10:34 pm GMT

JS: Check if an email is valid

Hello World! The sixth episode of the series - A CSS/JS trick in 5 minutes.
My first ever Dev.to article was about HTML forms, in the last part, I explained you how to check if an email is valid. I will do the same here while going a little bit deeper.

First We have to know how emails are done. In big lines, we know that their divided into two parts and always contain @. This w3 resource explains that better.

A base solution can be:

function checkEmailValidity (email) {  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)}
Enter fullscreen mode Exit fullscreen mode

This function will just check if the email contains one (and doesn't contain more) @. This is better when you want to be inclusive (you think it's better to have some fake email while annulling the possibility to reject the right ones).

We have to use regex to know if the email is valid, if you don't know how they work, check this:

A JavaScript Regular Expression (or Regex) is a sequence of characters that we can utilize to work effectively with strings. Using this syntax, we can search for text in a string, replace substrings in a string or extract information from a string.
Check this cool article to learn more about regex.

We could also use a more advanced regex to check other parameters such as first character, unallowed characters, or invalid domain names:

function checkEmailValidity (email) { if (/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(myForm.emailAddr.value))  {    return (true)  }    return (false)}
Enter fullscreen mode Exit fullscreen mode

If you need it I also did an article on how to check if a password is valid.

Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue :)


Original Link: https://dev.to/devlorenzo/js-check-if-an-email-is-valid-23m4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To