JQuery电子邮件验证无效

时间:2014-09-11 05:07:34

标签: javascript jquery validation

我是JQuery的新手,并编写了一个简单的验证来检查电子邮件地址。但它没有按预期工作。有人可以建议解决这个问题吗?

<script>
   $( "#email" ).blur(function() {  
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
if($( "#Email" ).val().match(mailformat))  
{  
alert("You have entered an valid email address!");   
}  
else  
{  
alert("You have entered an invalid email address!");    
}  
});
  </script>
</head>
<body>
<label for="email" id="email-ariaLabel">Your email address:</label>
 <input id="email" name="email" type="email" class="required" title="This is a required field" /> <span class="msg error">Not a valid email address</span>
 <span class="msg success">A valid email address!</span>

3 个答案:

答案 0 :(得分:2)

您的代码将在创建元素之前运行,因此不会附加处理程序。您应该将代码包装在$(document).ready()中,以便在创建元素之后运行代码。

此外,选择器区分大小写,您应使用$("#email").val()而不是$("#Email").val()

 $(document).ready(function(){
   $( "#email" ).blur(function() {  
   var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
   if($("#email").val().match(mailformat))  
   {  
     alert("You have entered an valid email address!");   
   }  
   else  
   {  
     alert("You have entered an invalid email address!");    
   } 
  });
})

答案 1 :(得分:1)

试试这个 -

<script>
   $( "#email" ).blur(function() {  
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
if($( "#email" ).val().match(mailformat))  
{  
   alert("You have entered an valid email address!");   
}  
else  
{  
   alert("You have entered an invalid email address!");    
}  
});
  </script>
</head>
<body>
<label for="email" id="email-ariaLabel">Your email address:</label>
 <input id="email" name="email" type="email" class="required" title="This is a required field" /> <span class="msg error">Not a valid email address</span>
 <span class="msg success">A valid email address!</span>

或者您只需将email的数据注释用作

即可
[StringLength(100, ErrorMessage = "Email can accept maximum 100 characters.")]
[RegularExpression("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+(?:[a-zA-Z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$", ErrorMessage = "Please enter valid email address.")]
public string email { get; set; }

答案 2 :(得分:0)

您可以参考下面的代码来解决Ur问题。

 <script>
       $( "#email" ).blur(function() {  
         var mailformat = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
         var emailTextField = $( "#email" ).val();
         if(!emailReg.test(emailTextField) || emailTextField.length == 0)  
         { 
           alert("You have entered an invalid email address!");
         }  
         else  
         {  
           alert("You have entered an valid email address!");
         }  
       });
    </script>