为什么此javascript验证总是失败

时间:2018-12-20 14:41:58

标签: javascript regex

我已经对电子邮件和密码进行了经典的输入验证,但是由于某种原因,我的逻辑不起作用,并且我无法弄清失败的部分。这是我从其他代码重构而来的代码,现在困扰着我很多

function Validation() {
  this.regex = {
    email: new RegExp(/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9-]+/),
    password: new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,13}/),
  },
  this.email = function () {
    let valElement = document.getElementById("mail");
    console.log(valElement);
    let valueR = valElement.value.toString();
    console.log(valueR);
    let erorrEl = document.getElementById("error");

    let validate_mail = valueR.length == 0 && this.regex.email.test(valueR);
    console.log(validate_mail);
    console.log(this.regex.email);
    if(!validate_mail){
      valElement.className = "invalid";
      erorrEl.innerHTML = "Please enter a correct email";
      erorrEl.className = "error active"
      console.log("not validated email");
      event.preventDefault();
    }else{

      valElement.className = "valid";
      erorrEl.innerHTML = "";
      erorrEl.className = "error"
      console.log("validated email");
    }
  }
  this.password = function () {
    let valElement = document.getElementById("pass");
    let valueR = valElement.value;
    let erorrEl = document.getElementById("error2");
    let validate_pass = valueR.length == 0 && this.regex.password.test(valueR);
    if(!validate_pass){
      valElement.className = "invalid";
      erorrEl.innerHTML = "Please enter a correct password";
      erorrEl.className = "error active"
      console.log("not validated password");
      event.preventDefault();
    }else{
      valElement.className = "valid";
      erorrEl.innerHTML = "";
      erorrEl.className = "error"
      console.log("validated password");
    }
  }
  this.form = function(){
    if(this.password && this.email){

    }else{

    }
  }
}

var Valdator = new Validation();
        Valdator.email();
        Valdator.password();

通常,我在另一个文件中调用这些Valdator电子邮件和密码功能,这是API的请求,但是这里的想法是相同的,我认为这不会有所作为

1 个答案:

答案 0 :(得分:2)

您的RegEx从未执行过,因为valueR.length == 0的计算结果为false,这会在执行第二部分之前使&&短路。请记住,如果您对两个语句进行“与”运算,并且第一个语句的取值为false,则不需要评估第二个语句,因为false && truefalse && false的取值为{{1} }。

话虽这么说,将false作为评估valueR.length == 0上的RegEx的前提是没有意义的-为什么我们要对长度为0的字符串运行RegEx?您应该将此逻辑翻转为valueR

并且将来请务必使用!=====,因为!==会使类型转换变得混乱。

==