正则表达式检查javascript中的电子邮件验证不起作用

时间:2016-03-03 05:56:14

标签: javascript

下面是我的javascript函数,它已经在运行......

但是当我尝试实现正则表达式检查电子邮件是否正确时,我的功能不起作用,并且不显示任何消息......

所以plz建议我如何实现这个。

<script language="javascript">
 function validateFields(){
   var error = '0';
   var emailpattern =/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/;

   if(document.getElementById('InvitationEmailAddress').value==""){
     document.getElementById('email_address_error').innerHTML = "Email address is required";
     error = '1';
   }

  if(document.getElementById('InvitationEmailAddress').value!="")
  {
    if(!InvitationEmailAddress.value.match(emailpattern)){  
     document.getElementById('email_address_error').innerHTML = "Email address is not valid";
     error = '1';
   }else{
     document.getElementById('email_address_error').innerHTML = "";
   }
 }


   if(document.getElementById('InvitationMessage').value==""){
     document.getElementById('message_error').innerHTML = "Welcome message is required";
     error = '1';
   }else{
     document.getElementById('message_error').innerHTML = "";
   } 
  if(error == 1){
     return false;
   }else{
     return true;
   }
 }
</script>

2 个答案:

答案 0 :(得分:0)

if(!InvitationEmailAddress.value.match(emailpattern)){

应该是:

if(!document.getElementById("InvitationEmailAddress").value.match(emailpattern)){

答案 1 :(得分:-1)

电子邮件regex = /^\w+([.-]?\w+)@\w+([.-]?\w+)(.\w{2,3})+$ /

此外,您每次都要解析DOM以搜索:InvitationEmailAddress元素

你可以将它保存在变量&amp;可以使用这个变量。

var inMsgEmRef = document.getElementById('InvitationEmailAddress');