Joppo
Joppo

Reputation: 739

jQuery validate with array does not work

Please consider the simple form with jQuery validation code below. Somehow I (still) go wrong with the syntax for the rules, as the validation does not work in this way (while I checked some sites on stackoverflow on this topic). How to describe the rule properly using arrays?

Please your help.

Code:

<form id="myForm" name="myForm" action="" method="post" autocomplete="on">
<label class="field2" for="productname[0]"> Product name 1 </label> <input id="productname[0]" type="text" name="productname[0]"> <br>
<label class="field2" for="productname[1]"> Product name 2 </label> <input id="productname[1]" type="text" name="productname[1]"> <br>
<input type="submit" name="submitForm" value="Submit Form">

<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/jquery.validate.js"></script>

<script>
$(function() {

    $("#myForm").validate({

    rules: {

            'productname[]': {
                required:true,
                minlength: 2,
                maxlength: 30,
            }

            } //rules
    }); //validate()

}); //function
</script>
</body>

Upvotes: 1

Views: 124

Answers (2)

YD1m
YD1m

Reputation: 5895

Seems problem is in your html markup. Try to modify:

<label class="field2" for="productname[0]"> Product name 1 </label> <input id="productname[0]" type="text" name="productname[]"> <br />
<label class="field2" for="productname[1]"> Product name 2 </label> <input id="productname[1]" type="text" name="productname[]"> <br />

Upvotes: 0

Daniel
Daniel

Reputation: 5024

I don't know what your back-end looks like but naming the fields [0] and [1] is unnecessary

<label class="field2" for="productname_1"> Product name 1 </label> <input id="productname_1" type="text" name="productname[]"> <br>
<label class="field2" for="productname_2"> Product name 2 </label> <input id="productname_2" type="text" name="productname[]"> <br>

The above should be sufficient, and work with the validation. The server will most likely take care of converting the post query string into an Array.

Upvotes: 2

Related Questions