使用自定义方法扩展JQuery验证插件

4

我添加了一个自定义验证方法来验证密码。但是,无论我得到的JSON是什么:

{"success":true}

or:

{"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");
                }
            });
        }
    });
});

你有什么想法,我做错了什么吗?

1个回答

7
您做错的事情是,在添加自定义方法时,您从未从中返回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');

你可以使用远程函数,而不是添加自定义方法:

$('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");
            }
        });                     
    }
});   

你可以在这里查看它的实际效果

你比我多7000个声望点,但徽章却比我少。徽章系统显然有问题。 - Sergio del Amo
感谢您指向远程函数。这是一个非常优雅的解决方案。 - Sergio del Amo
请将以下代码片段添加到您的远程解决方案中,以说明自定义远程消息:, messages: { password: { remote: jQuery.format("密码错误") } } - Sergio del Amo
声誉系统没有问题。我有373个答案,而你只有19个答案。我的答案没有产生足够的声誉来给我银牌或金牌,但它们被原始发布者接受了。 - Darin Dimitrov
1
我的意思是系统对你有误。你应该比我拥有更多的徽章。 - Sergio del Amo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接