验证电子邮件地址。(高级)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证电子邮件地址。(高级)相关的知识,希望对你有一定的参考价值。

The following javascript will validate an email address using strict rules when a form is submitted.
  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. ...

以上是关于验证电子邮件地址。(高级)的主要内容,如果未能解决你的问题,请参考以下文章

超实用的php代码片段

教程4 - 验证和权限

重定向时如何在 Safari 中保留 uri 片段?

Amazon SES 电子邮件地址未验证

如何在 Laravel 中验证电子邮件地址是不是是有效的 PayPal 电子邮件地址

电子邮件地址验证方法(订阅按钮)