jQuery Validate by ID and form group
jquery, jquery-validate
Solution
I also have a rule to allow one or both fields.
I don't see how your `require_from_group` rule is going to work when you're not using the `contact-method` class anyplace in your HTML markup. You'll need to add this `class`...
<input id="email" type="email" class="form-control contact-method" name="data[email]" placeholder="Email">
<input id="phone" type="text" class="form-control contact-method" name="data[phone]" placeholder="Phone">
I need to validate by `id` and not input `name` because my input `name` is `data[name]`
There are two workarounds...
When the `name` contains special characters like dots or brackets, you would simply surround the `name` with quotes...
jQuery(function($) {
$('#requestDemo').validate({
....
rules: {
"data[email]": {
require_from_group: [1, ".contact-method"]
},
....
DEMO 1: http://jsfiddle.net/umgjLvhd/
Declare the rule using the `.rules('add')` method instead of within `.validate()`...
$('.contact-method').each(function() {
$(this).rules('add', {
require_from_group: [1, $(this)]
});
});
DEMO 2: http://jsfiddle.net/mcotx2oh/
NOTE: No matter how you declare the rules, the `input` elements must still contain unique `name` attributes.
Problem
I need to validate by id and not input name because my input name is data[name]. I also have a rule to allow one or both fields. I can add the rules with id but I cannot combine both rules. Is there a way. ``` <input id="email" type="email" class="form-control contact-method" name="data[email]" placeholder="Email"> <input id="phone" type="text" class="form-control contact-method" name="data[phone]" placeholder="Phone"> ``` Js Code: ``` $('#requestDemo').validate({ // <- attach '.validate()' to your form debug: false, errorElement: "span", errorClass: "help-block", rules: { phoneInput: { require_from_group: [1, ".contact-method"] }, emailInput: { require_from_group: [1, ".contact-method"] } }, ```