验证密码在Javascript中匹配

时间:2015-04-20 22:31:24

标签: javascript jquery html ajax

我正在尝试验证两个密码字段并检查它们是否匹配,但即使两个输入框都有相同的密码,表单仍会出错。

JS

var validator = $("#signupform").validate({
  rules: {
    password: {
      required: true,
      minlength: 6
    },

    repeatpassword: {
      required: true,
      minlength: 6,
      equalTo: "#password"
    }

  },
  messages: {
    password: {
      required: "Provide a password",
      minlength: jQuery.format("Enter at least {0} characters")
    },
    repeatpassword: {
      required: "Repeat your password",
      minlength: jQuery.format("Enter at least {0} characters"),
      equalTo: "Your passwords do not match"
    }
  },
});

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 col-sm-6 col-md-6">
  <div class="form-group">
    <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
  </div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
  <div class="form-group">
    <input type="password" name="repeatpassword" id="repeatpassword" class="form-control input-lg" placeholder="Confirm Password" tabindex="6">
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

不确定你是否知道这一点,但是,“绝对要求你有<form></form>标签让jQuery Validate插件正常运行,或者根本不需要。” Read More

所以我添加了一个表单标签。

我认为密码的问题是,你这样做了:

jQuery.format("Enter at least {0} characters")

控制台出错:

  

“$。format已被弃用。请改用$ .validator.format。”;

所以我将您的代码更改为:

  

jQuery。验证器 .format(“输入至少{0}个字符”)

var validator = $("#signupform").validate({
  rules: {
    password: {
      required: true,
      minlength: 6
    },

    repeatpassword: {
      required: true,
      minlength: 6,
      equalTo: "#password"
    }

  },
  messages: {
    password: {
      required: "Provide a password",
      minlength: jQuery.validator.format("Enter at least {0} characters")
    },
    repeatpassword: {
      required: "Repeat your password",
      minlength: jQuery.validator.format("Enter at least {0} characters"),
      equalTo: "Your passwords do not match"
    }
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<form id="signupform">
  <div class="col-xs-12 col-sm-6 col-md-6">
    <div class="form-group">
      <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
    </div>
  </div>
  <div class="col-xs-12 col-sm-6 col-md-6">
    <div class="form-group">
      <input type="password" name="repeatpassword" id="repeatpassword" class="form-control input-lg" placeholder="Confirm Password" tabindex="6">
    </div>
  </div>
  <input type="submit" value="Submit">
</form>