远程验证时未定义的jQuery错误

时间:2015-04-02 08:49:27

标签: jquery jquery-validate

我正在远程验证字段,我收到以下错误:

Uncaught TypeError: Cannot read property 'call' of undefined.
jquery.validate.js:617 
n.extend.checkjquery.validate.js:423
n.extend.elementjquery.validate.js:271
n.extend.defaults.onfocusoutjquery.validate.js:366
ijquery.validate.js:1359  
(anonymous function)jquery-2.0.3.js:4676  
i.event.dispatchjquery-2.0.3.js:4360
i.event.add.y.handlejquery-2.0.3.js:4594
i.event.triggerjquery-2.0.3.js:4893  
i.event.simulatejquery-2.0.3.js:5009  
i.support.focusinBubbles.i.each.f   

这是我的代码:

 $("input[id$=txtCompanyName]").rules("add", {
                required: true,
                alphanumeric: true,
                remote: function() {
                    return {
                        url: "/Resources/wsResources.asmx/IsCompanyAvailable",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify({ company: $("input[id$=txtCompanyName]").val() }),
                        dataFilter: function(data) {
                            console.log(data);
                            var msg = JSON.parse(data);
                            if (msg.hasOwnProperty('d'))
                                return msg.d;
                            else
                                return msg;
                        }
                    };
                },
                messages: {
                    required: "This field is required",
                    alphanumeric: "Company name is not in correct format",
                    remote: $.validator.format("{0} already exists")
                }
            });

2 个答案:

答案 0 :(得分:1)

我认为您可能在PHP(或您的远程代码)中犯了错误。我当时正在研究它。如果你在写:

if(foo){echo true;}
else {echo false;}

尝试写作:

if(foo){echo "true";}
else {echo "false";}

它对我有用。在控制台中查看对ajax调用的响应,看看实际返回的是什么。

答案 1 :(得分:0)

  • remote方法已定义,插件中包含function()。您不会定义新函数来代替预期的对象文字。换句话说,只需follow the documentation并列出remote方法内的选项。

  • 如果您要使用jQuery将#{1}}方法应用于多个元素"以"结尾选择器,然后您必须.rules()括在jQuery .rules()中。

  • 确保在使用.each()规则时包括the additional-methods.js file

  • 您的许多选项都是默认选项,可以省略。默认情况下已发送该字段的alphanumericdata已经dataType等。

  • 您不会自己编写任何代码来处理服务器响应。 JSON方法已被编程为捕获&处理服务器响应。您的服务器端脚本只需要使用remotetrue或JSON字符串进行响应。

  • 您不会使用false参数占位符为remote定义自定义消息,因为没有参数。如果服务器端代码返回JSON字符串,则该字段无效,该字符串将自动成为错误消息。否则,您可以在{0}中为remote定义静态消息。

  • 我们看不到您的HTML或您对messages的来电。但是,请验证您是否只需拨打.validate()一次即可初始化表单上的插件;当你致电.validate()时,表格已经存在。您必须在每个字段元素上也有唯一的.validate()属性,否则插件将失败。

再次请参阅the documentation for remote

name