1

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>

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thnx for your comments (!). However your code does not seem to work when I use it. It does work when changing the name values (name="productname_1", name="productname_2". In my real code I have much more product names and related fields to check, which would require writing a lot of validation rules and the reason being why I tried the arrays. The solution suggested by YD1m seems to work.
0

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 />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.