4

I added a custom validation method to validate a password. However, it does not matter if the JSON I get is:

{"success":true}

or:

{"success":false}

The field password never validates.

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

Any idea, what I am doing wrong?

4

1 回答 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");
            }
        });                     
    }
});   

你可以在这里查看它的运行情况。

于 2009-06-23T19:23:20.387 回答