jquery - 使用 jQuery Validate 插件将规则传递给类

标签 jquery jquery-validate

我正在使用 jQuery 官方网站上提供的 jQuery 验证插件来验证我的表单。一切都很顺利,直到我必须传递规则,不是基于字段 name,而是基于 classid。我做不到。

这是我如何使用 name="comment" 将规则传递到字段的示例。

这是我的 jQuery 代码

$("#comForm").validate({
    rules: {
        comment: {
            required: true,
            minlength: 5,
            maxlength: 500
        }
    }
});

这是我的表格

  <form id="comForm" action="#" method="post" >
  <textarea rows="4" name="comment" placeholder="What do you think?" class="input-xxlarge" id="defaultform"></textarea></br>
  <textarea rows="4" name="othercomment" placeholder="What do you think?" class="input-xxlarge" id="defaultform"></textarea></br>
  <input type="submit" value="Rate!" class="btn btn-primary">
  </form>

假设我想将规则传递到具有默认表单 id 的每个字段或具有 input-xxlarge class 的所有字段。这可能吗?

最佳答案

是的,这是可能的,但你真的不应该使用重复的 id...它是无效的 HTML,并且会导致 JavaScript 问题。如果需要重复项,请使用 class

使用内置的rules()方法添加规则并按class分配它们。 See documentation.

然后使用 jQuery 的 .each()方法将规则应用于使用相同的所有匹配元素。

HTML:

<form id="myform">
    <textarea class="myclass" name="field1" ></textarea>
    <textarea class="myclass" name="field2" ></textarea>
</form>

jQuery:

$('#myform').validate({
    // your other rules and options
});

// the following method must come AFTER .validate()
$('.myclass').each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 5,
        maxlength: 500,
        messages: {
            required: "Required input",
            minlength: "Must be at least {0} characters",
            maxlength: "Must be less than {0} characters"
        }
    });
});

<强> Working DEMO


另外,类似于这个问题:

jQuery Validate set rule using wildcard to find target fields

关于jquery - 使用 jQuery Validate 插件将规则传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493850/

相关文章:

jquery - 如何在父 ul mouseout 上隐藏子 ul

javascript - 什么是验证诸如 mm/yyyy 之类的日期格式的正则表达式?

c# - 验证和 Asp.net Mvc 2.0 的最佳实践?

javascript - jQuery UI 对话框中的 jQuery 验证不起作用?

javascript - 编写自定义验证规则

.net - jQuery 日期验证 MVC 4 .Net 4.5.1 英国日期 "must be a date"错误

jquery - 登陆第一个 div,向下滚动到下一个 div,并禁用滚动回第一个 div。如何做到这一点?

javascript - 如果点击 <a> 如何防止 .slideup ? (注意: <a> is used to .加载html)

javascript - 从 Bootstrap 模式获取下拉文本

javascript - jquery 删除兄弟元素,在 IE7 中不起作用