使用自定义方法扩展 JQuery Validator Plugin [英] Extend JQuery Validator Plugin with custom method

查看:20
本文介绍了使用自定义方法扩展 JQuery Validator Plugin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了一个自定义验证方法来验证密码.但是,如果我得到的 JSON 是:

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

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

任何想法,我做错了什么?

Any idea, what I am doing wrong?

推荐答案

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

What you do wrong is that when you add your custom method you never return true or false from it. You return it in the ajax callback.

$.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 函数来代替添加自定义方法:

Instead of adding a custom method you could use the remote function:

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

您可以在这里查看它.

这篇关于使用自定义方法扩展 JQuery Validator Plugin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆