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

标签 jquery json validation jquery-plugins jquery-validate

我添加了自定义验证方法来验证密码。但是,我得到的 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/

相关文章:

javascript - 图标单击上的日期范围选择器事件

javascript - DataTable 1.10x jQuery 列过滤器通过输入文本框服务器端

javascript - 将 JSON 加载到 Angular

javascript - AngularJS ng-repeat 和 json 数据的问题

javascript - 当表单提交从一页转到另一页时如何制作加载进度条

javascript - 解析 JSON w/@ at 符号 (arobase)

.net - 如何处理在较新版本的 .NET(3.5 以上)中数据绑定(bind)期间发生的异常?

输入附加上的 jQuery 验证(Twitter Bootstrap)

validation - AFNetworking 2.0有效证书,仍然无法连接(错误1012)

javascript - 单击 Bootstrap 分页链接调用 jquery 函数