Jquery在添加规则时验证抛出错误

Posted

技术标签:

【中文标题】Jquery在添加规则时验证抛出错误【英文标题】:Jquery validate throwing error when adding a rule 【发布时间】:2017-04-09 05:18:28 【问题描述】:

当我的 js 页面加载并创建如下所示的规则时,我从 jquery.validate.js 库第 138 行抛出一个错误,提示“无法读取未定义的属性‘设置’”

settings = $.data( element.form, "validator" ).settings;

这是我要添加的规则和我要添加的表单

$('#zipCodeText').rules("add", 
  required: true,
  minlength: 5,
  maxlength: 5,
  messages: 
    required: "Required input",
    minlength: jQuery.validator.format("Please, 0 characters are necessary"),
    maxlength: jQuery.validator.format("Please, 0 characters are necessary")
  
);
@using (html.BeginForm("SaveLocation", "Manage", FormMethod.Post, new  @class = "form-horizontal", @id = "registerForm", role = "form" )) 
<div class="form-group">
  <label for="countryList">Country</label>
  <br />@Html.EnumDropDownListFor(m => m.Countries, null, new  @id = "countryList", @class = "selectpicker btn-group-lg" )
</div>

<div id="zipCodeGroup" class="form-group has-feedback" style="display: @(Model.Country == 0 ? " " : "none ");">
  <label for="zipCodeText">ZipCode</label>
  <input type="number" min="5" max="5" class="form-control input-lg" id="zipCodeText" placeholder="e.g. 94102" value="@Model.ZipCode">
  <label id="zipCodeMessage" style="display: none;"></label>
</div>
<div id="locationGroup" class="form-group has-feedback" style="display: @(Model.Country == 0 ? " none " : " ");">
  <label for="locationText">Location</label>
  <input type="text" min="4" max="40" class="form-control input-lg" id="locationText" placeholder="e.g. San Francisco" value="@Model.Location">
  <label id="locationMessage" style="display: none;"></label>
</div>

<input type="button" value="Save" id="yogaLocationSave" class="btn btn-primary btn-lg" />
<input type="button" value="Cancel" id="yogaLocationCancel" class="btn btn-default btn-lg" />

【问题讨论】:

在 html 中创建 zipCodeText 元素后是否设置规则? 是的,我只是单步执行它以确保在 js 之前首先呈现 HTML。我什至尝试将规则放在按钮点击中,所以在我点击表单上的按钮之前它甚至不会被创建! 【参考方案1】:

javascript 运行时错误:无法获取未定义或空引用的属性“设置””

必须首先通过在表单元素上调用.validate() 方法来初始化插件。

$('#yourform').validate( // <-- INITIALIZE the plugin on your form
    // any options, rules, or callbacks
);

【讨论】:

以上是关于Jquery在添加规则时验证抛出错误的主要内容,如果未能解决你的问题,请参考以下文章

在 TypeScript 中安装 jQuery 时出错

Lumen 提供验证错误的代码

以编程方式创建网站集时出错

加载时在 iframe 内容中添加客户端不显眼的验证规则

尝试访问 Thymeleaf 表单中的验证错误时出错

Odoo - 添加新字段时出错:ValidateError 验证字段拱时发生错误:视图架构的 XML 无效