0

At first, i have searched many but no article solved my problem.

This article make me know that using quote to validate array inputs.

My problem is how to validating length of array inputs. For more detail, plz read more bellow

In my HTML:

<form id="demo-form">
    <input type="text" name="product[]" id="p1">
    <input type="text" name="product[]" id="p2">
    <input type="text" name="product[]" id="p3">
    <input type="text" name="product[]" id="p4">
    <input type="submit value="submit">
</form>

This requires user has to enter at lease 2 products

Script

jQuery("#demo-form").validate({
    rules: {
        'product[]': {
            required: true,
            minlength: 2 //this only use to validate length of string inputed, not length of array products
        }
    },
});

How to validate length of array products?

Thanks

Community
  • 1
  • 1
Jonny Vu
  • 1,420
  • 2
  • 13
  • 32

1 Answers1

1
  1. Every text input must have unique name in order for this plugin to operate properly. Use product[0], product[1], product[2], etc.

  2. Use the require_from_group method to make sure at least two fields get filled out.

  3. Use the groups option to lump the four identical error messages into one.

Example:

jQuery("#demo-form").validate({
    // other rules & options
    groups: {
        myproducts: "product[0] product[1] product[2] product[3]"
    }
});

// assign the rule to all field names that start with 'product'
jQuery('[name^="product"]').each(function() {
    jQuery(this).rules('add', {
        require_from_group: [2, jQuery('[name^="product"]')]
    });
});

DEMO: http://jsfiddle.net/s960pyr0/

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Seem jquery.validation not supports array input much! Btw, your solutions resolved my problem. Thanks – Jonny Vu Feb 02 '16 at 08:29