In the following example, you will see how to use FormValidation with the
Bootstrap button group. Basically, we have multiple radios which are wrapper inside a
data-toggle="buttons"
element:
<div class="form-group row">
<label class="col-sm-3 col-form-label">Gender</label>
<div class="col-sm-9" id="genderContainer">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary"> <input type="radio" name="gender" value="male" /> Male </label>
<label class="btn btn-secondary"> <input type="radio" name="gender" value="female" /> Female </label>
<label class="btn btn-secondary"> <input type="radio" name="gender" value="other" /> Other </label>
</div>
</div>
</div>
Customizing icon position
You can ignore this section if you don't use the
Icon plugin. In order to show the feedback icon at the desired position, we need to hook on the
onPlaced
event:
icon: new FormValidation.plugins.Icon({
...
onPlaced: function(e) {
if (e.field === 'gender') {
document.getElementById('genderContainer').appendChild(e.iconElement);
}
}
}),
Revalidating the field
Bootstrap 4.3.1 prevents the default action of radio buttons when being used with data-toggle="buttons"
. So, we need to revalidate the field when it's changed manually:
const demoForm = document.getElementById('demoForm');
const fv = FormValidation.formValidation(demoForm, {
fields: {
gender: {
validators: {
notEmpty: {
message: 'The gender is required'
}
}
},
},
plugins: {
...
}
});
$(demoForm).find('[name="gender"]').on('change', function() {
fv.revalidateField('gender');
});
You should look at the
basic principle when integrating FormValidation with 3rd party libraries
Integrating with Bootstrap button group