电子邮件验证Jquery无法正常工作

时间:2015-10-28 09:18:42

标签: javascript jquery validation email

我一直致力于简单的电子邮件验证。但它没有用。

为什么它不起作用的任何想法?我做错了什么,还是应该以其他方式构建我的代码?

我做了这样的功能:

ImageButton btnsave = (sender) as ImageButton;

然后我在function IsEmail(email) { var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if(!regex.test(email)) { return false; } else { return true; } } 函数中调用该函数。

我的JS看起来像这样:

setupRegistration

4 个答案:

答案 0 :(得分:1)

@ Mario-Chueca是对的。您的代码大部分都正常工作,但是,无论电子邮件是否正确,您是否正在进行Ajax调用,因此未显示错误消息。您应该只在指定的电子邮件有效时进行ajax调用:

if(username != "" && email != "" && password != "" && IsEmail(email)){
    ajaxCall(username, email, password);
}  

我在下面添加了一个代码示例,以表明您的电子邮件验证(没有Ajax调用)正常工作。我已经包含了@Abdulla建议的if(!IsEmail(email){修正,我还添加了一个更复杂的正则表达式来自post



function IsEmail(email) {
  //var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  //More advanced regex to valid 99.99% of most emails in use, see https://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  var regex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
  if (!regex.test(email)) {
    return false;
  } else {
    return true;
  }
}

function doOutputMessage(type, message) {  
  $("#outputMessage").html("");
  $("#outputMessage").removeClass();
  $("#outputMessage").hide();
  if (type == "error") {
    $("#outputMessage").addClass("error").fadeIn("fast");
  } else if (type == "success") {
    $("#outputMessage").addClass("success").fadeIn("fast");
  }

  $("#outputMessage").text(message);
  $("#outputMessage").show();
}


//if (IsEmail('john.doe@stackoverflow.com')) {

//  doOutputMessage('success', 'valid email')
//}



if (!IsEmail('john.doe#stackoverflow.com')) {

  doOutputMessage('error', 'invalid email')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outputMessage">Test</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用之前的一些建议,但也改变了这一点,错误不会停止ajax调用:

var error_email=false;
if(!IsEmail(email)){
    error_email=true;
    doOutputMessage("error", "mailen är fel förfan");
}

if(password == ""){
    doOutputMessage("error", "Fill in your desired password!");
}

if(username != "" && email != "" && password != "" && !error_email){
    ajaxCall(username, email, password);
} 

答案 2 :(得分:0)

删除此处的false

if(!IsEmail(email){

regex应为

regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

Live DEMO

How to Find or Validate an Email Address

答案 3 :(得分:0)

请尝试:

function IsEmail(email){
    var reg = /^[a-zA-Z0-9\.\-\+]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/
    return reg.test(email)
}
相关问题