I'm using jQuery Validate to validate my form. The problem is that I have a form with multiple select boxes (dynamic number) and it has a dynamic name -> answers[$question['id']]
I've seen some scripts when there's a fixed name you can use that to address all the input fields like so.
$('#form').validate({
rules: {
"answers[]" = "required"
}
});
But in my example this is not possible, Any ideas? Thanks!
Firstly,
it's not "answers[]" = "required"
it's "answers[]": "required"
Notice the colon in place of your equals sign.
$('#form').validate({
rules: {
"answers[]": "required"
}
});
Secondly, that would only assign the required rule to a single field with name="answers[]".
If you want to easily assign this rule to multiple fields with name="answers[1]", name="answers[2]", name="answers[3]", etc., then you'll need to do one of two things...
1) Declare the required rule inline...
using class:
<input type="text" name="answers[1]" class="required" />
<input type="text" name="answers[2]" class="required" />
<input type="text" name="answers[3]" class="required" />
OR with HTML5:
<input type="text" name="answers[1]" required="required">
<input type="text" name="answers[2]" required="required">
<input type="text" name="answers[3]" required="required">
And jQuery:
$('#form').validate(); // initialize the plugin
DEMO #1: http://jsfiddle.net/7JHWf/
2) Or assign the rule dynamically using the rules() method to all fields with a name starting with answers:
$('#form').validate(); // initialize the plugin
// assign the rules
$('input[name^="answers"]').each(function() {
$(this).rules('add', {
required: true
});
});
DEMO #2: http://jsfiddle.net/7JHWf/1/
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