我需要使用jQuery Validate的自定义规则来比较表单的两个输入文本字段。
我尝试了以下代码
//Our validation script will go here.
$(document).ready(function(){
//custom validation rule - text only
$.validator.addMethod("NotEqualTo",
function(value, element) {
return ???;
}, "Two Properties are matching"
);
$("#frmUpdatePassword").validate({
onfocusout: true,
rules: {
NewPassword: {
NotEqualTo: '#OldPassword' }
},
messages: {
NewPassword: {
NotEqualTo: "Two Properties are having same values"
}
}
});
});
HTML TextBox
是
<input type="password" id="OldPassword" name="OldPassword" />
<input type="password" id="NewPassword" name="NewPassword" />
请帮助我如何以通用方式比较不等于两个属性,而不仅仅是比较这两个字段。
答案 0 :(得分:0)
自定义验证规则应为
$.validator.addMethod('NotEqualTo', function (value, element, param) {
var str1 = value || '';
var str2 = $(param).val() || '';
return $.trim(str1) != $.trim(str2);
}, 'Invalid: Two values are matching');
规则应
rules: {
NewPassword: {
NotEqualTo: '#OldPassword'
}
}
答案 1 :(得分:-1)
请尝试这个,我遇到了同样的问题,并通过以下提及代码解决。
//Our validation script will go here.
$(document).ready(function(){
//custom validation rule - text only
$.validator.addMethod("NotEqualTo", function(value, element) {
var OldPassword = $("#OldPassword").val() || null;
if(value == OldPassword)
{
return true; //Error fire!
}
else
{
return false; //Error Not fire!
}
}, "Two Properties are matching");
$("#frmUpdatePassword").validate({
onfocusout: true,
rules: {
NewPassword: {
NotEqualTo: true;
}
},
messages: {
NewPassword: {
NotEqualTo: "Two Properties are having same values"
}
}
});
});
你的所有代码都没问题!只是更新验证方法。