电子邮件验证的正则表达式

时间:2014-10-14 22:29:53

标签: regex validation email-validation

我正在制作密码和电子邮件页面,需要使用注册表验证电子邮件。 我的问题是我使用的注册表只会验证@符号之后所有电子邮件都有效,我需要一个完整的证明注册表验证并确保其“.com”或英语替代(拼写)检查不会接受)最后任何人都可以帮忙吗?

我需要它的代码:

    <script type="text/javascript">

     function checkForm(form)
    {
    if(form.email.value == "") {
      alert("Error: Username cannot be blank!");
      form.email.focus();
      return false;
    }
    re = /^\w+$/;
    if(!re.test(form.email.value)) {
      alert("Error: Username must contain only letters, numbers and underscores!");
      form.email.focus();
      return false;
    }

    if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
      if(form.pwd1.value.length < 6) {
        alert("Error: Password must contain at least six characters!");
        form.pwd1.focus();
        return false;
      }
      if(form.pwd1.value == form.email.value) {
        alert("Error: Password must be different from Username!");
        form.pwd1.focus();
        return false;
      }
      re = /[0-9]/;
      if(!re.test(form.pwd1.value)) {
        alert("Error: password must contain at least one number (0-9)!");
        form.pwd1.focus();
        return false;
      }
      re = /[a-z]/;
      if(!re.test(form.pwd1.value)) {
        alert("Error: password must contain at least one lowercase letter (a-z)!");
        form.pwd1.focus();
        return false;
      }
      re = /[A-Z]/;
      if(!re.test(form.pwd1.value)) {
        alert("Error: password must contain at least one uppercase letter (A-Z)!");
        form.pwd1.focus();
        return false;
      }
    } else {
      alert("Error: Please check that you've entered and confirmed your password!");
      form.pwd1.focus();
      return false;
    }

    alert("You entered a valid password: " + form.pwd1.value);
    return true;
  }

   </script>

   <form ... onsubmit="return checkForm(this);">
   <p>email: <input type="email" name="email"></p>
   <p>Password: <input type="password" name="pwd1"></p>
   <p>Confirm Password: <input type="password" name="pwd2"></p>
   <p><input type="submit"></p>
   </form>

1 个答案:

答案 0 :(得分:1)

real regex to properly validate email addresses according to the spec is massive,,可能不是你想要实际做的。请记住,.NET,.COM,.TRAVEL,.CA和many many more是有效的顶级域名,并且可以向他们发送电子邮件。

相反,请考虑进行非常简单的正则表达式验证(检查@符号)并发送验证电子邮件以确认电子邮件地址有效。依靠用户正确输入他们疯狂的电子邮件。

请参阅this relevant Programmers discussion