【问题标题】:Error:Uncaught TypeError: $(...).valid is not a function while using ('#form').valid()错误:未捕获的类型错误:$(...).valid 在使用 ('#form').valid() 时不是函数
【发布时间】:2016-10-08 15:58:07
【问题描述】:

这是我的页面,我想通过 jquery 函数检查表单是否有效。代码如下:

<div class="wrapper wrapper-content animated fadeInRight">

    <div class="row" style="width:80%;padding-top:20px;margin-left:3%;">
        @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "addNominationForm"}))
        {
            @Html.AntiForgeryToken()

            <div class="white-bg" style="padding-left:2%">

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group" style="padding-top:10px">

                    @Html.Label("Nomination Category", htmlAttributes: new { @class = "control-label col-md-3 requiredfeild", style = "text-align: left" })
                    <div>
                        @Html.DropDownListFor(model => model.AwardId, @ViewBag.Awards as SelectList, "Select", new { htmlAttributes = new { @class = "form-control" }, id = "Award", style = "width:25%" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.Label("Resource From", htmlAttributes: new { @class = "control-label col-md-3 requiredfeild", style = "text-align: left" })
                    <div>
                        <label> @Html.RadioButtonFor(model => model.SelectResourcesBy, "Project", new { htmlAttributes = new { @class = "form-control" }, id = "ProjectRadioButton" })Project</label>
                        &nbsp;
                        <label> @Html.RadioButtonFor(model => model.SelectResourcesBy, "Department", new { htmlAttributes = new { @class = "form-control" }, id = "DepartmentRadioButton" })Department</label>
                    </div>
                </div>

                <input type="hidden" name=ManagerId value=@ViewBag.ManagerId>

                <div class="form-group" id="projectInput">
                    @Html.Label("Project", htmlAttributes: new { @class = "control-label col-md-3 requiredfeild", style = "text-align: left" })
                    <div>
                        @Html.DropDownListFor(model => model.ProjectID, @ViewBag.ProjectsUnderCurrentUser as SelectList, "Select", new { htmlAttributes = new { @class = "form-control" }, id = "SelectedProject", style = "width:25%" })
                    </div>
                </div>

                <div class="form-group" id="departmentInput">
                    @Html.Label("Department", htmlAttributes: new { @class = "control-label col-md-3 requiredfeild", style = "text-align: left" })
                    <div>
                        @Html.DropDownListFor(model => model.DepartmentId, @ViewBag.DepartmentsUnderCurrentUser as SelectList, "Select", new { htmlAttributes = new { @class = "form-control" }, id = "SelectedDepartment", style = "width:25%" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.Label("Resource Name", htmlAttributes: new { @class = "control-label col-md-3 requiredfeild", style = "text-align: left" })
                    <div>
                        @Html.DropDownListFor(model => model.ResourceId, @ViewBag.Resources as SelectList, "Select", new { htmlAttributes = new { @class = "form-control" }, id = "Resources", style = "width:25%" })
                    </div>
                </div>

                <div class="form-group" style="padding-bottom:10px">
                    @Html.Label("Is PLC ?", htmlAttributes: new { @class = "control-label col-md-3", style = "text-align: left" })
                    <div>
                        @Html.CheckBoxFor(model => model.IsPLC, new { htmlAttributes = new { @class = "form-control" }, id = "IsPlcCheckbox" }) Yes
                    </div>
                </div>
            </div>
            <br />
            <div class="form-group">
                <div>
                    <div id="Criterias">
                        <table class="table table-hover issue-tracker white-bg" id="criteriaTable"></table>
                    </div>
                    @Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
                </div>
            </div>
            <br />
            <div class="form-group white-bg" style="padding-top:10px;padding-bottom;padding-left:2%">
                @Html.Label("Comment", htmlAttributes: new { @class = "control-label col-md-2 requiredfeild", style = "text-align: left" })
                <div>
                    @Html.TextAreaFor(model => model.MainComment, new { htmlAttributes = new { @class = "form-control" }, id = "managerComment", style = "min-width: 80%", rows = "7", placeholder = "If candidate is selected as winner, this text will be shared across the company" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-3">
                    <input type="submit" name="submit" value="Save Draft" id="saveButton" class="btn btn-warning btnSameSize" />
                    <input type="submit" name="submit" value="Submit" id="submitButton" class="btn btn-success-green btnSameSize" onclick="return checkCriteriaComments();" />
                    <input type="button" value="Cancel" class="btn btn-danger btnSameSize" onclick="location.href='@Url.Action("Dashboard", "Dashboard")'" />
                </div>
            </div>

        }
    </div>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">


    function checkCriteriaComments() {
        var comments = 0;

         if($("#addNominationForm").valid())
         {
               alert("valid form");
         }    


        $(".criteriaComment").children("textarea").each(function (data) {
            if ($(this).val().trim())
                comments++;
        });

        if (!$("#Award").val()) {
            $("#Award").tooltip({ title: "Select Award.", placement: 'right' }).tooltip('show');
            return false;
        }

        else if (comments < 1) {
            $(".criteriaComment").children("textarea").first().tooltip({ title: "Enter at least one criteria comment.", placement: 'right' }).tooltip('show');
            return false;
        }
        else if (!$("#managerComment").val()) {
            $("#managerComment").tooltip({ title: "Enter main comment.", placement: 'right' }).tooltip('show');
            return false;
        }
        else {
            swal({
                title: "Add Nomination",
                text: "Do you want to nominate this candidate?",
                type: "info",
                showCancelButton: true,
                confirmButtonColor: "#88a364",
                confirmButtonText: "Yes!",
                cancelButtonText: "No!",
                closeOnConfirm: false,
                closeOnCancel: false
            },
              function (isConfirm) {
                  if (isConfirm) {
                      debugger;
                      var model = $('#addNominationForm').serialize()

                      $.ajax({
                          type: 'post',
                          url: '@Url.Action("AddNomination", "Nomination")',
                          data: JSON.stringify({ model: model,submit:"Submit" }),
                          contentType: "application/json; charset=utf-8",
                          success: function (data) {
                              swal({
                                  title: "Nominated Successfully",
                                  showCancelButton: false,
                                  confirmButtonColor: "#88a364",
                                  confirmButtonText: "Ok"
                              },
                              function () {
                                  if (isConfirm) {
                                      window.location.href = '@Url.Action("Dashboard", "Dashboard")';
                                  }
                              });
                          }
                      });
                  } else {
                      swal("Cancelled", "Nomination Cancelled");
                  }
              });

            return true;
        }

    }
    }

</script>

这是我的模型:

  public class NominationViewModel
    {
        [Required(ErrorMessage = "Select Award")]
        public int AwardId { get; set; }

        public int NominationId { get; set; }
        public int ManagerId { get; set; }

        [Required(ErrorMessage = "Select Resource")]
        public int ResourceId { get; set; }

        [Required(ErrorMessage = "Select Project")]
        public int? ProjectID { get; set; }

        [Required(ErrorMessage = "Select Department")]
        public int? DepartmentId { get; set; }
        public bool IsPLC { get; set; }
        public bool? IsSubmitted { get; set; }

        public string MainComment { get; set; }

        [Required(ErrorMessage = "Select Project or Department")]
        public string SelectResourcesBy { get; set; }  //from project or from department

        [Required(ErrorMessage = "Please provide comment against criteria")]
        public IList<CriteriaCommentViewModel> Comments { get; set; }

        public NominationViewModel()
        {
            Comments = new List<CriteriaCommentViewModel>();
        }

    }

在这里,当我在浏览器中调试脚本代码时,它在 valid() 函数上给出了“Uncaught TypeError: $(...).valid is not a function”这个错误。如何解决这个问题?提前谢谢...

【问题讨论】:

  • 你在if(("#addNominationForm").valid())中缺少$
  • 即使在添加 $ 之后,它仍然显示相同的错误

标签: jquery razor jquery-validate unobtrusive-validation


【解决方案1】:

这个错误

Error:Uncaught TypeError: $(…).valid is not a function while using ('#form').valid

主要是由于插件重叠。所以检查插件并正确包含插件。我有那个错误并以适当的方式添加了 jquery-validating 插件。

【讨论】:

    【解决方案2】:

    “未捕获的类型错误:$(...).valid 不是函数”

    As per the documentation,您只能在调用.validate() 之后的某个时间使用.valid()

    validate()需要在使用该方法检查表单之前调用。

    由于您使用的是 Microsoft 框架,.validate()jquery.validate.unobtrusive.js 插件自动构建和调用。

    您将不得不检查您的实时 DOM 以查看调用 .validate() 的位置,并确保您对 .valid() 的调用移动到 .validate() 调用之后的某个位置

    【讨论】:

    • 如何根据 viewmodel 中给出的数据注释检查有效字段?
    • @AbhishekJadhav,插件会自动处理,.valid() 只是强制它以编程方式检查。请参阅您的文档以了解 Unobtrusive Validation 插件。
    • 我只是想在jqery函数中检查视图上的字段是否有效(基于数据注释)..我怎样才能实现它?
    • @AbhishekJadhav,这一切都是自动完成的! 请参阅您的文档以了解 Unobtrusive Validation 插件。 否则,我已经充分解释了您收到您所描述的错误消息的原因。
    • 如果我在 valid() 之前调用 validate() 那么它会给出同样的错误:“Uncaught TypeError: $(...).validate is not a function”
    【解决方案3】:

    可能的原因是,您没有正确链接您的库或缺少库。结果无法识别$(whatever).valid()的函数。

    【讨论】:

    • 很遗憾,这是不正确的。请参阅上面的评论。
    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2022-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    相关资源
    最近更新 更多