How to check array of inputs using validate plugin jquery

I am the new jquery validation plugin, but I would like to know how we validate an array of input fields using the validation plugin.

Below is the html code.

<form id="transport-form"> <input type="text" name="qty[]" id="qty1"> <input type="text" name="qty[]" id="qty2" > <input type="text" name="qty[]" id="qty3"> <input type="text" name="qty[]" id="qty4"> <input type="submit value="submit"> </form> 

and jquery code below

 jQuery("#transport-form").validate({ rules: { 'qty[]': { required: true } }, }); 

But every time I click the "Submit" button, it only checks the first value. other values โ€‹โ€‹of the same name are not checked. Please, help.

+26
jquery jquery-validate validation
Jul 10 '14 at 7:08
source share
9 answers

Sometimes we need to check an array of input elements: for example -

 <form name="signupForm" class="cmxform" id="signupForm" method="get" action=""> <select name="category[]" id="cat_1"> <option value="">Select One</option> <option value="1">aa</option> <option value="2">bb</option> <option value="3">cc</option> <option value="4">dd</option> </select> <select name="category[]" id="cat_2"> <option value="">Select One</option> <option value="5">ee</option> <option value="6">ff</option> <option value="7">gg</option> <option value="8">hh</option> </select> <select name="category[]" id="cat_3"> <option value="">Select One</option> <option value="9">ii</option> <option value="10">jj</option> <option value="11">kk</option> <option value="12">ll</option> </select> <input class="submit" type="submit" value="Submit"> </form> 

Now we will use the jquery validation jquery.validate.js plugin to validate the form. The condition is that the user will have to choose a category from each drop-down list. The script for verification will be lower:

 <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.validate.js"></script> <script type="text/javascript"> $(document).ready(function() { // validate the comment form when it is submitted $("#signupForm").validate({ rules: { "category[]": "required" }, messages: { "category[]": "Please select category", } }); }); </script> 

Now the problem is that readymade jquery.validate.js only checks the first element of the category []. Therefore, we need to change it a little.

In jquery.validate.js we can find a function called checkForm, we must change it as shown below:

 checkForm: function() { this.prepareForm(); for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) { if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) { for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) { this.check(this.findByName(elements[i].name)[cnt]); } } else { this.check(elements[i]); } } return this.valid(); } 

I just got this solution from http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/ I hope this helps someone.

+41
Jul 10 '14 at 7:43
source share
โ€” -

You can pass an option to ignore part of the field name; As for the original post comments, there are many options for using the style name [] in HTML, especially using PHP.

 $("#my-form").validate({ submitHandler: function(form) { form.submit(); }, ignore: [], rules: { 'category[]': { required: true } } }); 
+15
Jan 27 '15 at 20:29
source share

I noticed that using jQuery validate plugin I will only define the first element with a specific name.

Another way to make the jQuery validation plugin also detect all inputs that go beyond the first can be unique. So you can replace:

 <input type="text" name="qty[]" /> <input type="text" name="qty[]" /> <input type="text" name="qty[]" /> <input type="text" name="qty[]" /> 

from:

 <input type="text" name="qty[0]" /> <input type="text" name="qty[1]" /> <input type="text" name="qty[2]" /> <input type="text" name="qty[3]" /> 
+8
Dec 01 '16 at 16:04
source share

This is the best solution that I have found, and which I am currently using in my project:

 // Adding rule to each item in qtyi list jQuery('[id^=qty]').each(function(e) { jQuery(this).rules('add', { minlength: 2, required: true }); }); 
+7
May 16 '17 at 7:19
source share

First, for jQuery to distinguish between elements, you need to have a separate identifier for each element. This can be done programmatically when you add inputs. Then you need to check all inputs with a common name at the same time. To do this, create a custom validator using the addMethod () function, as described in the documentation.

 jQuery.validator.addMethod("allRequired", function(value, elem){ // Use the name to get all the inputs and verify them var name = elem.name; return $('input[name="'+name+'"]').map(function(i,obj){return $(obj).val();}).get().every(function(v){ return v; }); }); 

You can use this, as a rule, for your array elements:

 $('form').validate( { rules: { "nbPieces[]": "allRequired" }, submitHandler : function(form, event) { event.preventDefault(); //... etc } }); 

In order for errors to display correctly on empty fields, you may need to override the errorPlacement parameter from the check ...

+3
May 16 '17 at 18:09
source share

You need to index each item

Below is the html code.

 <form id="transport-form"> <input type="text" name="qty[0]" id="qty1"> <input type="text" name="qty[1]" id="qty2" > <input type="text" name="qty[2]" id="qty3"> <input type="text" name="qty[3]" id="qty4"> <input type="submit value="submit"> </form> 

and jquery code below

 jQuery("#transport-form").validate({ rules: { 'qty[]': { required: true } }, }); 
+2
Mar 06 '17 at 14:38
source share

Here's the solution without specifying indexing on the array.

 <form> <div>Name: <p> <input name="name_ct[]" id="id_ct0" type="text" class="form-control" placeholder="Add Variant 1 Name"> </p> </div> <input type="button" value="Add Variant" /> <input type="submit" /> </form> 

js code

 $(document).ready(function () { $.validator.addMethod("mytst", function (value, element) { var flag = true; $("[name^=name_ct]").each(function (i, j) { $(this).parent('p').find('label.error').remove(); $(this).parent('p').find('label.error').remove(); if ($.trim($(this).val()) == '') { flag = false; $(this).parent('p').append('<label id="id_ct'+i+'-error" class="error">This field is required.</label>'); } }); return flag; }, ""); $("form").validate({ ignore: '', rules: { "name_ct[]": { mytst:true } }, submitHandler: function () { //you can add code here to recombine the variants into one value if you like, before doing a $.post form.submit(); alert('successful submit'); return false; } }); var j = 1; $('input[type="button"]').click(function () { $('form div').append('<p><input name="name_ct[]" id="id_ct' + j + '" type="text" class="form-control" placeholder="Add Variant ' + j + ' Name " ></p>'); j++; }); }); 

you can see here in js fiddle: https://jsfiddle.net/q0d76aqx/42/

+1
Jan 04 '18 at 9:23
source share

I used the solution proposed by AsgarAli Khanusiya, but JQuery.Validator shows a label with an error message in the same cases in the wrong place. This is because it stores previously displayed messages. If the user makes the same mistake with another element in the collection, then the validator displays the label in the previous place, and does not generate a new label next to the element with the problem. I overridden the errorsFor method to solve this:

 $.validator.prototype.errorsFor = function (element) { var name = this.idOrName(element); var elementParent = element.parentElement; return this.errors().filter(function() { return $(this).attr('for') == name && $(this).parent().is(elementParent); }); } 
0
Oct 18 '18 at 8:21
source share

jQuery Form Validator is a multi-functional and multilingual jQuery plugin that makes it easy to validate user input while maintaining your HTML markup with javascript code. Despite the fact that this plugin has a wide range of verification functions, it is designed for minimal jQuery network traffic. This is achieved by grouping the validation functions in โ€œmodulesโ€, which allows you to load only those functions that are necessary to validate a specific form.

 <form action="" id="registration-form"> <p> E-mail <input name="email" data-validation="email"> </p> <p> User name <input name="user" data-validation="length alphanumeric" data-validation-length="3-12" data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)"> </p> <p> Password <input name="pass_confirmation" data-validation="strength" data-validation-strength="2"> </p> <p> Repeat password <input name="pass" data-validation="confirmation"> </p> <p> Birth date <input name="birth" data-validation="birthdate" data-validation-help="yyyy-mm-dd"> </p> <p> Country <input name="country" id="country" data-validation="country"> </p> <p> Profile image <input name="image" type="file" data-validation="mime size required" data-validation-allowing="jpg, png" data-validation-max-size="300kb" data-validation-error-msg-required="No image selected"> </p> <p> User Presentation (<span id="pres-max-length">100</span> characters left) <textarea name="presentation" id="presentation"></textarea> </p> <p> <input type="checkbox" data-validation="required" data-validation-error-msg="You have to agree to our terms"> I agree to the <a href="..." target="_blank">terms of service</a> </p> <p> <input type="submit" value="Validate"> <input type="reset" value="Reset form"> </p> </form> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script> <script> $.validate({ modules : 'location, date, security, file', onModulesLoaded : function() { $('#country').suggestCountry(); } }); // Restrict presentation length $('#presentation').restrictLength( $('#pres-max-length') ); </script> ... 
-2
Nov 17 '17 at 11:33
source share



All Articles