无法使用正则表达式验证电子邮件地址

时间:2015-10-22 03:55:24

标签: javascript regex validation email-validation

我想运行我的页面来测试我的验证是否有效。但是,它不适用于电子邮件地址。我已为电子邮件地址添加了正则表达式。它没有完全验证。

我输入了a@live而没有输入.com它能够接受它。我认为这是因为我输入input="email"纠正我错了。是因为错误的正则表达式还是我放置代码的方式?

的javascript

function validate(){
     var fname =  document.getElementById('fname').value;
         var lname =  document.getElementById('lname').value;
    var email =  document.getElementById('email').value;
         var emailReg = '/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/';
    var re = /^[\w ]+$/;
         var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

     if(email=="")
     {
        alert('Please fill in email fields');   
        return false;
     } 
 else if(fname=="")
     {
        alert('Please fill in first name fields');  
        return false;
     } 
     else if(lname=="")
     {
        alert('Please fill in last name fields');   
        return false;
     } 
     return true;
}

register.php

    <form name="registrationForm" method="post" id="registrationForm" class="registrationForm" action="processRegister.php" onclick="validate">
        <div class='input1'>
            <span id="emailAddress-label" class="help"></span> 
              <input class="regemailaddr" id="emailAddress" name="emailAddress" type="email" placeholder="Email Address " value="" required>
        </div>
          <br> 
            <span id="fname-label" style="margin-bottom:" class="help"></span>
                <input id="fname" name="fname" type="text" placeholder="First Name " class="fname" value="" required>
            <span id="lname-label" class="help"></span> <input id="lname" name="lname" type="text" placeholder="Last Name " class="lname" value="<?php echo $user_profile["lname"]; ?>" required> 
          <br>
               <button class="greybtn" type="submit" id="submitButton">Submit</button>
                <button class="cancelbtn" type="button" id="cancelButton" onclick="window.location='#';return false;">Cancel</button>
</form>

1 个答案:

答案 0 :(得分:0)

您已定义正则表达式

var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

但是你没有对它进行测试

var isEmail = emailReg.test(email);