jqueryjquery-validate

How to validate array of array inputs Jquery?


How do we validate array of array input boxes using jquery validation plugin?

Below is html code.

<form id="transport-form">
  <div class="form-group>
    <label> Room1</label>
    <input type="text name="child[0]" value="2">
    <input type="text" name="age[0][]">
    <input type="text" name="age[0][]">
  </div>
  <div class="form-group>
    <label> Room2</label>
    <input type="text name="child[1]" value="2">
    <input type="text" name="age[1][]">
    <input type="text" name="age[1][]">
  </div>
  <input type="submit value="submit">
</form>

I have no of child input child[*] and accept to each children an age. If I input 2 children there age need to be filled mandatory.

and jquery code is below

jQuery("#transport-form").validate({
        rules: {
            'age[*][]': {
                required: function(element){
                            check age is between 1 to 12 
                        }
            }
        },
    });

Solution

  • Be careful with missing quotes.

    <div class="form-group">

    Try this. It adds generic rules to all current age inputs (name starting with age[ ) - alternatively give the age inputs a class and use that as selector instead

    $(() => {
    
      $("#transport-form").validate({ ...  }); // your existing validation
    
      $('input[name^="age["]').each(function() {
        $(this).rules('add', {
          required: true,
          range: [1, 12],
          messages: {
            required: "Please enter the age for all children.",
            range: "Age must be between 1 and 12."
          }
        });
      });
    });
    

    If you wish, you can add room number:

    $('input[name^="age["]').each(function() {
      const inputElement = $(this); // Capture the input element
      inputElement.rules('add', {
        required: true,
        range: [1, 12],
        messages: {
          required: function() {
            // Find the index of the closest .form-group relative to its siblings
            let index = inputElement.closest('.form-group').index() + 1; // 0 based index
            return `Please enter the age for children in room ${index}`;
          },
          range: "Age must be between 1 and 12."
        }
      });
    });