Reputation: 4828
I have input
tag fields which has name
attribute in array
for i.e.
<div class="form-group">
<label class="col-sm-2 control-label">
<span style="color: red;">*</span>
Title</label>
<div class="col-sm-8 general-title tooltip-demo">
<input type="text" name="form[1][title]" id="title" value="" size="64" class="form-control" data-toggle="tooltip" data-placement="top" data-html="true" title="" required="required" data-original-title="Enter Notification Title"> </div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
<span style="color: red;">*</span>
Title 2</label>
<div class="col-sm-8 general-title tooltip-demo">
<input type="text" name="form[2][title]" id="title" value="" size="64" class="form-control" data-toggle="tooltip" data-placement="top" data-html="true" title="" required="required" data-original-title="Enter Notification Title"> </div>
</div>
I know, i can do validation like
$(document).ready(function() {
$("#frmforgot").validate({
rules: {
form[1][title]: {
required: true
},
form[2][title]: {
required: true
}
}
});
});
But i don't want to separate each validation rule, because i have 30 different fields so i don't want to write 30 * 2
rules.
If anyone know easy way, please suggest me.
Thanks in advance
Upvotes: 2
Views: 1876
Reputation: 98758
You can use the .rules()
method to assign any rules to the fields in bulk.
It's this simple...
$(document).ready(function() {
$("#frmforgot").validate();
$('input[name^="form"]').each(function() {
$(this).rules('add', {
required: true
});
});
});
In your case, it does not matter that the naming is using array format. The input[name^="form"]
selector is looking for any input
with a name
starting with the letters form
.
DEMO: jsfiddle.net/3e9d4v7q/
It's a moot point since you already have required="required"
on those input
elements, so you do not need to assign this rule again. The jQuery Validate plugin will simply use any HTML5 attribute to assign the corresponding rule automatically.
DEMO 2: jsfiddle.net/3e9d4v7q/1/
Upvotes: 3
Reputation: 1529
You could create your rules before you pass them into the validate function -
var rules = {};
$('input[name^=form]:text').each(function() {
rules[this.name] = { required: true };
});
$(document).ready(function() {
$("#frmforgot").validate({
rules: rules
});
});
Upvotes: 2