我正在尝试使用jquery验证器进行验证。每件事情都是第一次运作良好。
但是从第二次开始,如果我没有更改密码字段中的任何内容,如果我转到确认密码部分,理想情况下密码会显示错误,但同时确认密码也显示错误,"confirm password not matches to password."
确认密码只有在输入与密码不匹配的密码后才会显示错误。
是否有针对此问题的解决方案或我是否需要编写自己的自定义方法来扩展验证器方法。
这是我试过的:
$(document).ready(function(){
$("#cp").validate(validateChangePswrdForm("changePasswordForm"));
});
var validateChangePswrdForm = function() {
var that = this;
return {
rules: {
password: {
required: true,
minlength: 8,
},
confirmpassword: {
equalTo: "#password"
}
},
messages: {
password: {
required: "password is required",
minlength: 5
},
confirmpassword: {
required: "confirm password is required",
minlength: 5
}
},
submitHandler: function(fId, evt) {
var serForm = $(fId).serialize();
changepassword(fId, evt)
}
}
};
var changepassword = function(){
alert('Validated');
};

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="cp">
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-8 col-sm-7">
<form method="post" role="form" autocomplete="off" name="changePasswordForm" id="changePasswordForm">
<div class="alert alert-danger changepassword-error hidden">
</div>
<div class="form-group">
<label for="password">password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="password">
</div>
<div class="form-group reg-form col-sm-7 padLeft">
<label for="confirmpassword">Confirm Password</label>
<input type="password" class="form-control noradius" name="confirmpassword" id="confirmpassword" placeholder="Confirm Password">
</div>
<div class="btn-toolbar">
<button type="submit" class="btn">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
&#13;
答案 0 :(得分:2)
您的代码:
$("#cp").validate(....
第一次一切正常
它根本无法工作。如果您将.validate()
方法附加到<div>
(id="cp"
),则不会发生任何事情。要初始化插件,您只能将此方法附加到<form>
元素。
此外,您不能将两个参数传递给submitHandler
函数。它只被指定处理一个代表form
对象的参数。
messages
对象中的值只能包含表示自定义错误消息的字符串。您为从未声明的规则以及非字符串的值定义了消息。
这是有效的:
$(document).ready(function() {
$("#changePasswordForm").validate({
rules: {
password: {
required: true,
minlength: 8,
},
confirmpassword: {
equalTo: "#password"
}
},
messages: {
password: {
required: "password is required",
// minlength: 5 // <- this must be a string!
},
confirmpassword: {
required: "confirm password is required",
// minlength: 5 // <- this must be a string!
}
},
submitHandler: function(fId) {
var serForm = $(fId).serialize();
changepassword()
}
});
});
var changepassword = function() {
alert('Validated');
};