未定义Jquery Validator

时间:2011-08-08 22:00:45

标签: jquery asp.net-mvc asp.net-mvc-3 jquery-validate

我正在尝试向动态输入字段添加验证。我正在做的基本上是隐藏并显示一个字段(在1中同时具有登录和注册形式),如下所示:

<div id="RegBoxStorage" style="display: none;">
    @Html.LabelFor(m => Model.Name)
    @Html.TextBoxFor(m => Model.Name)
    @Html.ValidationMessageFor(m => m.Name)
</div>
@using (Html.BeginForm("Login", "Auth", FormMethod.Post, new { id = "AuthForm" }))
{
<div id="RegBox" style="display: none;">
</div>
<div id="LoginBox">

    @Html.LabelFor(m => Model.Email)
    @Html.TextBoxFor(m => Model.Email)
    @Html.ValidationMessageFor(m => m.Email)

    @Html.LabelFor(m => Model.Password)
    @Html.TextBoxFor(m => Model.Password)
    @Html.ValidationMessageFor(m => m.Password)
</div>
<input type="submit" id="BtnAuthSub" value="Login" />
or <a id="ToggleAuth" href="#">Sign Up</a>
}

剧本:

$('#AuthForm').removeData("validator");
$('#AuthForm').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this.authForm); // error here

插件:

(function ($) {
  $.validator.unobtrusive.parseDynamicContent = function (selector) {
    //use the normal unobstrusive.parse method
    $.validator.unobtrusive.parse(selector); //Error here

    //get the relevant form
    var form = $(selector).first().closest('form');

    //get the collections of unobstrusive validators, and jquery validators
    //and compare the two
    var unobtrusiveValidation = form.data('unobtrusiveValidation');
    var validator = form.validate();

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
      if (validator.settings.rules[elname] == undefined) {
        var args = {};
        $.extend(args, elrules);
        args.messages = unobtrusiveValidation.options.messages[elname];
        //edit:use quoted strings for the name selector
        $("[name='" + elname + "']").rules("add", args);
      } else {
        $.each(elrules, function (rulename, data) {
          if (validator.settings.rules[elname][rulename] == undefined) {
            var args = {};
            args[rulename] = data;
            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
            //edit:use quoted strings for the name selector
            $("[name='" + elname + "']").rules("add", args);
          }
        });
      }
    });
  }
})($);

因此,当用户点击ToggleAuth时,我会将内容从RegBoxStorage移至表单内的RegBox。现在我需要手动将验证添加到输入中。所有不显眼的验证属性都已经存在。所以从answer开始,我试了一下并说$.validator is undefined

但是表单的其他部分实际上已经过验证,表明验证工作正常,我同时引用了jquery.validation和jquery.validation.unobtrusive验证。可能是什么问题?

我还从这个blog获取了插件扩展名。

1 个答案:

答案 0 :(得分:7)

检查几件事:

  • 您已写入扩展程序,但仍在部分脚本中使用$.validator.unobtrusive.parse(this.authForm) - 请确保使用parseDynamicContent。

  • 确保在插件代码之前引用validation.js和validation.unobtrusive.js.

  • 确保您的脚本部分位于jQuery document.ready函数内,并在插件后执行。