Monday, 5 September 2016

javascript - Regex: Email validation that allows only hyphens in the middle of the domain and top-level domain



I know this is been asked tons of times before , but I haven't found anything that really meets all the conditions that an email address must meet to be considered valid.




Considering the following as the structure of an email address :



part1@part2.part3.part4



  • part1=username


  • part2=domain


  • part3 and part4 =top-level domain





These are all the conditions that must be met:




  1. An email address must not accept white spaces

  2. An email address must not end in a dot or a character other than a letter or a number

  3. Only one @ sign is allowed

  4. There can not be a special character before or after the at sign

  5. There can not be a special character before or after the domain dot (the dot after part2 of the email address)

  6. You can not enter two or more dots in a row in the username


  7. In the domain , between @ and the dot, the characters that are next to the @ and the dot must be a letter or number, in the middle the only special character allowed is the hyphen.

  8. The same in step 7 goes for the top-level domain(part 3 and part 4 or the email)



This is the regular expression I currently using :



^([\w\.\-]+)@([\w\-]+)((\.(\w){2,9})+)$


But it does not meet conditions :4,5,6,7 and 8




I'm just trying to figure out how to complement my regular expression and learn in the process.





The only special characters allowed in the email address are : dots, hyphens,underscores and the at sign



Here's a list of invalid emails



mkyong – must contains “@” symbol




mkyong123@.com – domain can not start with dot “.”



mkyong()*@gmail.com – email’s is only allow character, digit, underscore and dash



mkyong@%*.com – email’s tld is only allow character and digit



mkyong..2002@gmail.com – double dots “.” are not allow



mkyong.@gmail.com – email’s last character can not end with dot “.”




mkyong@mkyong@gmail.com – double “@” is not allow



mkyong@gmail.com.1a -email’s tld which has two characters can not contains digit



Valid:



mkyong@yahoo.com



mkyong-100@yahoo.com




mkyong.100@yahoo.com



mkyong111@mkyong.com



mkyong-100@mkyong.net



mkyong.100@mkyong.com.au



mkyong@1.com




mkyong@gmail.com.com



mkyong-100@yahoo-test.com


Answer



This is the best I have been able to do as per your list of valid and invalid email addresses:



^([\w-]|(?



DEMO



Updated:



^([\w-]|(?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...