gpt4 book ai didi

jquery - 使用自定义方法扩展 JQuery Validator 插件

转载 作者:行者123 更新时间:2023-12-01 00:05:21 25 4
gpt4 key购买 nike

我添加了自定义验证方法来验证密码。但是,我得到的 JSON 是否为:

并不重要
{"success":true}

或者:

{"success":false}

字段密码永远不会验证。

$(document).ready(function () {
// Ad custom validation
$.validator.addMethod('authenticate', function (value) {
$.getJSON("./json/authenticate.do", { password: value }, function (json) {
return (json.success == true) ? true : false;
}
);
}, 'Wrong password');

$('form#changePasswordForm').validate({
rules: {
repeat_new_password: { equalTo: "#new_password" },
password: { authenticate: true }
}, submitHandler: function (form) {
$(form).ajaxSubmit({
dataType: "json",
success: function (json) {
alert("foo");
}
});
}
});
});

知道我做错了什么吗?

最佳答案

你做错的是,当你添加自定义方法时,你永远不会从中返回 true 或 false。您可以在 ajax 回调中返回它。

$.validator.addMethod('authenticate', function (value) { 
$.getJSON("./json/authenticate.do",{ password: value }, function(json) {
// This return here is useless
return (json.success == true) ? true : false;
});
// You need to return true or false here...
// You could use a synchronous server call instead of asynchronous
}, 'Wrong password');

您可以使用 remote 而不是添加自定义方法。功能:

$('form#changePasswordForm').validate({
rules: {
repeat_new_password: {
equalTo: "#new_password"
},
password : {
// This will invoke ./json/authenticate.do?password=THEVALUE_OF_THE_FIELD
// and all you need to do is return "true" or "false" from this server script
remote: './json/authenticate.do'
}
},
messages: {
password: {
remote: jQuery.format("Wrong password")
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
dataType: "json",
success: function(json) {
alert("foo");
}
});
}
});

您可以实际查看 here .

关于jquery - 使用自定义方法扩展 JQuery Validator 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1034377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com