0

I am trying to add validation for a form

$('#reportForm').validate({
    rules: {
      'report[invoices_attributes][0][invoice_type]' :
  {
    required: true,
    'report[invoices_attributes][0][invoice_type]':true

  }
  }
  });

reportForm is the id of my form. All of my input fields name values will be like 'report[invoices_attributes][indexnr]...' ( as I am using nesting attributes and there can be 0 or more elements )

For this, I want to match the input name value for all with a regex like : /^report\[invoices_attributes\]\[[0-9]\](.*)/

How can this be added to the rule field for input name value (currently 'report[invoices_attributes][0][invoice_type]'), to match all the fields I'm interested in ?

  • You cannot do it like that. When declaring rules inside of the `rules` object of `.validate()`, you can only declare the rule one field at a time. You also cannot have a layout where all fields being validated share the same `name` attribute. Each field must have a unique `name`. Or a single "grouping" of checkboxes/radio buttons can share a `name`. This is all spelled out in the documentation. – Sparky May 28 '18 at 15:57
  • And under each `name` in your scenario can only be a listing of rules, not more field names. – Sparky May 28 '18 at 15:58

1 Answers1

0

First, I would entirely avoid Allman style code formatting in JavaScript.


When declaring rules inside of the rules object of .validate(), you can only declare the rule one field at a time...

$('#reportForm').validate({
    rules: {
        'report[invoices_attributes][0][invoice_type]': {
            required: true,
        },
        'report[invoices_attributes][1][invoice_type]': {
            required: true,
        },
        'report[invoices_attributes][2][invoice_type]': {
            required: true,
        },
        // etc.
    }
});

If you want to declare on multiple fields, then use the .rules() method along with a jQuery .each() and any appropriate jQuery selector that will target your group.

$('.myfields').each(function() {
    $(this).rules('add', {
        required: true
    });
});

You also cannot have a layout where all fields being validated share the same name attribute. Each field must have a unique name. Or a single "grouping" of checkboxes/radio buttons can share a name. There is no workaround for this.

If you're only needing basic rules that can simply be declared by boolean, then you can use inline attributes instead of .rules() method or rules object.

<input name="foo" required="required" ....

alternatively by class...

<input name="foo" class="required" ....

More info: https://stackoverflow.com/a/9056425/594235

Sparky
  • 98,165
  • 25
  • 199
  • 285