如何在 jQuery Validate 中标记必填字段

发布于 2024-09-10 18:17:01 字数 279 浏览 1 评论 0原文

我正在使用 jQuery Validate 和 xVal 来验证输入表单。这很好用。 但是,我确实想用星号 (*) 或类似的内容标记我的必填字段,以显示实际需要的字段。

我可以手动执行此操作,但由于我已经使用 xVal 生成了验证规则,所以我认为我可以根据提供的规则自动标记必填字段。

有没有办法连接到 xVal 或 jQuery Validate 来检索规则,或者以某种方式让它们标记我的必填字段?

我正在使用最新版本的 jQuery 和 jQuery Validate。

谢谢

I'm using jQuery Validate and xVal to validate in input forms. This works great.
However, I do want to mark my required fields with an asterix (*) or something like that to show which field is actually required.

I could do this by hand, but since I already generate my validation rules with xVal I thought I could mark the required fields automatically based on the provided rules.

Is there a way to hook into either xVal or jQuery Validate to retrieve the rules, or somehow make them mark my required fields?

I'm using the latest versions of jQuery and jQuery Validate.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌伤ぢ 2024-09-17 18:17:01

required 类赋予表单元素,并使用以下代码

$(document).ready(function() {
     $('<span style="color:red;">*</span>').insertAfter('.required');
});

这会将“*”附加到具有 required 类的每个元素

希望它有帮助

Give the class required to the form elements, and use the following code

$(document).ready(function() {
     $('<span style="color:red;">*</span>').insertAfter('.required');
});

This will attach "*" to every elements with required class

Hope it helps

黒涩兲箜 2024-09-17 18:17:01

这是可能的

  1. 获取表单中的所有输入
  2. 迭代并查找输入是否具有规则 required
  3. 如果是,找到该输入的标签
  4. 在标签文本末尾附加 *

您的代码将如下所示

    $.each($("#you-form input"), function( index, element ) {
      var rule =  $(element).rules() ; // this will get the rules for each input
      if(rule && rule.required) {
        //find label and append red *
      }
    });

This is possible

  1. Get all the inputs in form
  2. Iterate and find if the input has rule required
  3. If Yes, find the label of that input
  4. Append * at the end of the label text

Your code will look something like this

    $.each($("#you-form input"), function( index, element ) {
      var rule =  $(element).rules() ; // this will get the rules for each input
      if(rule && rule.required) {
        //find label and append red *
      }
    });
往日情怀 2024-09-17 18:17:01

最简单的方法可能是创建一个单独的“规则”变量,并将其传递给 jQuery 和其他函数。这个其他函数将循环遍历它并标记所有必填字段。

It is probably easiest to make a separate "rules" variable which you pass to both jQuery and some other function. This other function would loop through it and mark all required fields as such.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文