Validate an email address. (advanced)


/ Published in: JavaScript
Save to your folder(s)

The following JavaScript will validate an email address using strict rules when a form is submitted.


Copy this code and paste it in your HTML
  1. ...
  2.  
  3. <head>
  4.  
  5. ...
  6.  
  7. <script language="JavaScript" type="text/javascript">
  8. function emailCheck(emailStr) {
  9. var checkTLD=1;
  10. var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
  11. var emailPat=/^(.+)@(.+)$/;
  12. var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
  13. var validChars="\[^\\s" + specialChars + "\]";
  14. var quotedUser="(\"[^\"]*\")";
  15. var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
  16. var atom=validChars + '+';
  17. var word="(" + atom + "|" + quotedUser + ")";
  18. var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
  19. var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
  20. var matchArray=emailStr.match(emailPat);
  21. if (matchArray==null) {
  22. alert("You must supply a valid email address.");
  23. return false;
  24. }
  25. var user=matchArray[1];
  26. var domain=matchArray[2];
  27. for (i=0; i<user.length; i++) {
  28. if (user.charCodeAt(i)>127) {
  29. alert("The supplied email user name contains invalid characters.");
  30. return false;
  31. }
  32. }
  33. for (i=0; i<domain.length; i++) {
  34. if (domain.charCodeAt(i)>127) {
  35. alert("The supplied email domain contains invalid characters.");
  36. return false;
  37. }
  38. }
  39. if (user.match(userPat)==null) {
  40. alert("The supplied email address contains invalid characters.");
  41. return false;
  42. }
  43. var IPArray=domain.match(ipDomainPat);
  44. if (IPArray!=null) {
  45. for (var i=1;i<=4;i++) {
  46. if (IPArray[i]>255) {
  47. alert("The supplied email IP address is invalid.");
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. var atomPat=new RegExp("^" + atom + "$");
  54. var domArr=domain.split(".");
  55. var len=domArr.length;
  56. for (i=0;i<len;i++) {
  57. if (domArr[i].search(atomPat)==-1) {
  58. alert("The domain name does not seem to be valid.");
  59. return false;
  60. }
  61. }
  62. if (checkTLD && domArr[domArr.length-1].length!=2 &&
  63. domArr[domArr.length-1].search(knownDomsPat)==-1) {
  64. alert("The supplied email address must end in a well known domain or two letter " + "country code.");
  65. return false;
  66. }
  67. if (len<2) {
  68. alert("The supplied email address is missing a hostname.");
  69. return false;
  70. }
  71. return true;
  72. }
  73. </script>
  74.  
  75. ...
  76.  
  77. </head>
  78. <body>
  79.  
  80. ...
  81.  
  82. <form id="form1" name="form1" method="post" onSubmit="return emailCheck(this.email.value)" action="">
  83.  
  84. ...

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.