jQuery Validator - 自定义方法在有效时不会隐藏错误

时间:2011-07-06 07:41:22

标签: javascript jquery ajax validation

我有一个自定义验证器通过ajax请求检查可接受值的数据库的值。我一开始以为它没有隐藏错误消息,因为请求是异步完成的,所以它可能无法及时返回true或false以使验证程序识别出来。

我关闭异步并且仍然显示错误消息。我怎么能让它消失?

通过控制台记录,确实返回true,但错误消息仍然存在。我试图明确地隐藏消息,但验证器仍假定为false并且无法提交。

jQuery.validator.addMethod("validZip", function(value, element){
    var _id = $(element).attr("id");
    $.ajax({
        url: '/xpress/wp-admin/admin-ajax.php',
        data: {action:"test_checkZip", zip:value},
        type:"POST",
        asyc: false,
        success: function(response){
            if (response== 0){
                return false;
            } else {
                //$("label[for="+_id+"][class=error]").hide();
                return true;
            }
        } 
    });
}, '*');

4 个答案:

答案 0 :(得分:2)

正如Nicola指出的那样,你的回调中有一个拼写错误。 除此之外,它是返回true / false的回调函数,所以实际上你的validZip函数仍然返回'undefined'。

试试这个:

jQuery.validator.addMethod("validZip", function(value, element){
    var _id = $(element).attr("id");
    var isValid = false;
    $.ajax({
        url: '/xpress/wp-admin/admin-ajax.php',
        data: {action:"test_checkZip", zip:value},
        type:"POST",
        asyc: false,
        success: function(response){
            isValid = response!= 0;
        } 
    });
    return isValid;
}, '*');

答案 1 :(得分:1)

我认为您正在检查result我不应该查看response吗?

    success: function(response){
        if (response == false){
            return false;
        } else {
            //$("label[for="+_id+"][class=error]").hide();
            return true;
        }
    } 

答案 2 :(得分:1)

可能是因为你有:

asyc: false,

而不是:

async: false,

答案 3 :(得分:1)

您使用了上一个问题的错误答案代码,请在该问题中查看我的答案,看看有什么问题。无论如何你应该这样做:

jQuery.validator.addMethod("validZip", function(value, element){
    var _id = $(element).attr("id");
    var return_value;
    $.ajax({
        url: '/xpress/wp-admin/admin-ajax.php',
        data: {action:"test_checkZip", zip:value},
        type:"POST",
        async: false,
        success: function(response){
            if (result == 0){
                return_value = false;
            } else {
                //$("label[for="+_id+"][class=error]").hide();
                return_value = true;
            }
        }
        return return_value; //HERE you have to return
    });
}, '*');

问题是你在嵌套函数中返回值,而不是验证函数。

希望这会有所帮助。干杯