I am trying to validate the two inputs having same name with jquery validator ..
<script src='
http://code.jquery.com/jquery-latest.min.js '></script>
<script src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js'></script>
<script>
$(document).ready(function(){
$('#frm').validate();
$("[name=inp_text]").each(function(){
$(this).rules("add", {
required: true,
checkValue: true
});
});
$.validator.addMethod("checkValue", function(value, element) {
var response = ((value > 0)&&(value <= 100))||((value == 'test1')||(value =='test2'));
return response;
}, "invalid value");
})
</script>
<form id='frm' method='post'>
<input type='text' name='inp_text'/><br>
<input type='text' name='inp_text'/><br>
<input type='submit' name=''/>
</frm>
but when I run this code it only validates first inputs and second inputs gets simply ignored
I have also tried using <input type='text' name='inp_text[]'/><br>
but still not working.
what should I change...?
Thanks in advance
"I am trying to validate the two inputs having same name with jquery validator ..."
<input type='text' name='inp_text'/>
<input type='text' name='inp_text'/>
"but when I run this code it only validates first inputs and second inputs gets simply ignored"
You cannot have two input
fields of type="text"
with the same name
or this plugin will not work properly. The name
attribute must be unique. (One exception to the name
being unique, is that "groupings" of checkbox or radio inputs will share the same name
as the corresponding submission is a single point of data. However, the name
must still be unique to each grouping of checkbox and radio elements.)
"what should I change...?"
Make each name
attribute unique.
<input type='text' name='inp_text[1]'/>
<input type='text' name='inp_text[2]'/>
Then use the "starts with" selector, ^=
...
$("[name^=inp_text]").each(function () {
$(this).rules("add", {
required: true,
checkValue: true
});
});
Working DEMO: http://jsfiddle.net/PgLh3/
NOTES: You can also target elements by id
when using the rules('add')
method, however for this case, nothing is solved because the plugin still requires a unique name
on each input
element.
Add a configuration like the following like rules or messages
multipleInputSharedName: {
inp_text: true
}
Change code in jquery.validate.js Method name: elements
replace the following
if ( this.name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
with the following
if ( (!validator.settings.multipleInputSharedName[this.name] && this.name in rulesCache) || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With