验证插件 - ajax调用消息

时间:2013-02-28 22:12:36

标签: php jquery jquery-validate

我正在使用1.9.0 jquery版本,以及此验证插件:

http://docs.jquery.com/Plugins/Validation

我想从PHP文件中下载JSON格式的消息,如下所示:

    messages: {
        remote: function() {
            return $.ajax({
                url: 'http://localhost/My/index.php/form/validate/messages',
                type: "POST",
                }).done(function(messages) {
                    return messages;
                }
            );
         }
    }

然而,它根本不起作用,不显示消息,进行ajax调用,什么都没有。你能帮帮我这个吗?

2 个答案:

答案 0 :(得分:0)

试试这样:

$.ajax({
        url: 'http://localhost/My/index.php/form/validate/messages',
        type: 'POST',
        dataType: 'json',
        success: function (results) {
            //your data here in results
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
         alert("error");
        }
    });

在ServerSide上显示“错误”时出现问题。你需要调试它。您可以使用Firebug Network Console在浏览器中检查结果或网络控制台。

答案 1 :(得分:0)

使用remote规则时,请参阅文档以获取示例:

http://docs.jquery.com/Plugins/Validation/Methods/remote#options

remote规则用于将特定字段的内容与数据库进行比较...例如检查名称或密码是否已存在。 不能用于简单地将错误消息列表转储回插件。就插件而言,您只为一个规则设置一条错误消息。请参阅:http://jsfiddle.net/zga8y/

我真的不明白你想要做的目的。通常,每个规则的错误消息都会设置一次,但不会更改。

动态更改特定字段上的消息,您可以使用the rules('add') method。您甚至不必触及规则来覆盖消息。

$("#myinput").rules("add", {
    messages: {
        required: "Required input",
        minlength: jQuery.format("Please, at least {0} characters are necessary")
    }
});

或者,您可以覆盖任何或所有类似的消息:

jQuery.extend(jQuery.validator.messages, {
    required: "This field is required.",
    remote: "Please fix this field.",
    email: "Please enter a valid email address.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date (ISO).",
    number: "Please enter a valid number.",
    digits: "Please enter only digits.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    accept: "Please enter a value with a valid extension.",
    maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
    minlength: jQuery.validator.format("Please enter at least {0} characters."),
    rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
    range: jQuery.validator.format("Please enter a value between {0} and {1}."),
    max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
    min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});