DEV Community

loading...

Discussion on: JS: Check if an email is valid

Collapse
inhuofficial profile image
InHuOfficial • Edited

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:-

function cev(email) 
{
 if (/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/.test(email))
  {
    if(email.indexOf("..") == -1){
        return email + ": valid";
    }
  }
    return email + ": not valid";
}
Enter fullscreen mode Exit fullscreen mode

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!

Forem Open with the Forem app