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 :)
Subscribe to our newsletter!
A loooong, and fun, weekly recap for you
Free PDF version of my articles
Highly customizable inbox
That's --> free <-- and you help me!
Not bad but it will miss the edge cases:
For example
valid
firstname+lastname@example.com: valid ✔
email@example.museum: valid ✔
firstname-lastname@example.com: valid ✔
email@123.123.123.123: valid ✔
invalid
#@%^%#$@#$@#.com: not valid ✔
email@-example.com: valid ❌
email@example..com: not valid ✔
Abc..123@example.com: valid ❌
email..email@example.com: valid ❌
Tested here: jsfiddle.net/za5cs1rh/1/
May I suggest:-
A bit longer and still not 100% perfect but much closer. Also someone smarter than me can probably adjust the regex to include the check for a double full stop / period as I have to check that separately which makes the function untidy!
Tested here: jsfiddle.net/za5cs1rh/2/
With that being said even Google Chrome things some of those that aren't valid are valid so I suppose it doesn't matter!