如何验证电子邮件

时间:2014-03-10 03:50:41

标签: javascript html validation

我需要添加以向此表单添加以下特征但我被卡住了。任何帮助将非常感激。谢谢

  1. 一个或多个单词字符
  2. 正好一个签到
  3. 一个或多个单词字符
  4. 正好一个句点两个或多个字符是a-z, A-Z,0-9,句号或连字符

    <!DOCTYPE html>
      <html>
      <head>
      <script>
        function validateForm()
        {
          var x=document.forms["myForm"]["email"].value;
          var atpos=x.indexOf("@");
          var dotpos=x.lastIndexOf(".");
          if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
          {
             alert("Not a valid e-mail address");
             return false;
          }
        }
      </script>
    </head>
    
    <body>
      <form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
        Email: <input type="text" name="email">
        <input type="submit" value="Submit">
      </form>
    </body>
    

3 个答案:

答案 0 :(得分:1)

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
};

此功能适用于您的情况

像这样称呼它

if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
  

请记住,不存在100%的正则表达式电子邮件检查!

结帐此链接

https://stackoverflow.com/a/2855946/2630817

答案 1 :(得分:0)

试试这个:

<script>        
   function validateForm(){

       var email=document.forms["myForm"]["email"].value;

       var filter = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

       if (!filter.test(email)) {
           alert("Not a valid e-mail address");
           return false;
       }
       return true;
   }
</script>

答案 2 :(得分:0)

试试这个纯粹的javascript:

function checkEmail() {

    var email = document.getElementById('txtEmail');
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email.value)) {
    alert('Please provide a valid email address');
    email.focus;
    return false;
 }