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

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

问题描述

我添加了一种自定义验证方法来验证密码.但是,我得到的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');

您可以使用远程函数来代替添加自定义方法:

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插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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