You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery-Validate中require_from_group按name选择分组的实现方法问询

Using name Selectors with jQuery Validation's require_from_group

Great question! The require_from_group method accepts any valid jQuery selector as its second parameter, so you can absolutely use name-based selectors here by leveraging jQuery's attribute selector syntax.

Here's how to do it:

First, let's assume your form inputs have unique name attributes like this:

<form id="myform">
  <input type="text" name="mobile_phone" />
  <input type="text" name="home_phone" />
  <input type="text" name="work_phone" />
</form>

Then, in your validation configuration, use the [name="your-input-name"] syntax to target each input by its name, separated by commas for multiple elements:

$("#myform").validate({
  rules: {
    mobile_phone: {
      require_from_group: [1, '[name="mobile_phone"], [name="home_phone"], [name="work_phone"]']
    },
    home_phone: {
      require_from_group: [1, '[name="mobile_phone"], [name="home_phone"], [name="work_phone"]']
    },
    work_phone: {
      require_from_group: [1, '[name="mobile_phone"], [name="home_phone"], [name="work_phone"]']
    }
  }
});

Pro Tip: Simplify with Pattern Matching

If your input names follow a consistent pattern (like all ending with _phone), you can use a more concise attribute selector to avoid listing every single name:

$("#myform").validate({
  rules: {
    mobile_phone: {
      require_from_group: [1, '[name$="_phone"]'] // Matches any input with a name ending in "_phone"
    },
    // Repeat the same rule for home_phone and work_phone
  }
});

The key takeaway here is that require_from_group doesn't restrict you to class or ID selectors—any selector that jQuery can parse will work, including name-based attribute selectors.

内容的提问来源于stack exchange,提问作者user1032531

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:55:40