问题
Am new to jquery validation plugin but i would like to know how do we validate array of input boxes using validation plugin..
Below is 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 is below
jQuery("#transport-form").validate({
rules: {
'qty[]': {
required: true
}
},
});
But everytime i click submit it is validating only the first value. rest all the values of same name are not validated. Please help.
回答1:
Sometimes we need to validate 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 jquery validation plugin jquery.validate.js for validating the form. The condition will be that user will have to choose category from each dropdown. The script for validation will be as below -
<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 the readymade jquery.validate.js only validates the first element of category[]. So, we need to modify it a little bit.
In jquery.validate.js, we can find a function named checkForm, we have to modify it as 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/ hope this helps someone..
回答2:
You can pass an option in to ignore part of a field name; As for the original posts comments, there are plenty of use-cases for having a name[] style name in HTML, especially using PHP.
$("#my-form").validate({
submitHandler: function(form) {
form.submit();
},
ignore: [],
rules: {
'category[]': {
required: true
}
}
});
回答3:
I noticed that the jQuery validate plugin i use will only detect the first element with a specific name.
Another way to make the jQuery validate plugin also detect all the inputs beyond the first could be by making the names unique. So you could replace:
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
with:
<input type="text" name="qty[0]" />
<input type="text" name="qty[1]" />
<input type="text" name="qty[2]" />
<input type="text" name="qty[3]" />
回答4:
This is the Best solution I found and 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
});
});
回答5:
You need to make indexing of each elements
Below is 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 is below
jQuery("#transport-form").validate({
rules: {
'qty[]': {
required: true
}
},
});
回答6:
First, for jQuery to distinguish between the elements you need to have a different id per element. This can be done programmatically when you add the inputs. Then what you need to do is to verify all inputs with common name at once. For that, 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 on your array elements :
$('form').validate(
{
rules: {
"nbPieces[]": "allRequired"
},
submitHandler : function(form, event) {
event.preventDefault();
//... etc
}
});
For the errors to appear correctly on the empty fields though, you may need to override the errorPlacement option from validate...
回答7:
Here the solution without giving indexing to 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/
回答8:
I've used solution proposed by AsgarAli Khanusiya but JQuery.Validator shows label with error message in same cases in the wrong place. It happens because it stores previously shown messages. If user make same mistake with different item in the collection then validator displays label in the previous place instead of generation new label near element with issue. I've overrided '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);
});
}
回答9:
jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code. Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular 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>
...
来源:https://stackoverflow.com/questions/24670447/how-to-validate-array-of-inputs-using-validate-plugin-jquery