jQuery-Validate中require_from_group按name选择分组的实现方法问询
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

