An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
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)}
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)}
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To