Excluding field by given condition

Consider the following example. It asks you about the Javascript framework you like most. You can choose one from the list of popular Javascript frameworks such as Angular, Ember, React, Vue.
If your favorite framework is not in the list, you must fill its name in a text box. You can use the callback validator validator to validate this input:
FormValidation.formValidation(
form,
{
fields: {
framework: {
validators: {
notEmpty: {
message: 'Please select a framework'
}
}
},
otherFramework: {
validators: {
callback: {
message: 'Please specific the framework',
callback: function(input) {
const selectedCheckbox = form.querySelector('[name="framework"]:checked');
const framework = selectedCheckbox ? selectedCheckbox.value : '';
return (framework !== 'other')
// The field is valid if user picks
// a given framework from the list
? true
// Otherwise, the field value is required
: (input.value !== '');
}
}
}
},
},
plugins: {
...
},
}
);
The logic inside the callback function is quite simple and easy to understand. The problem comes when you submit the form, the otherFramework field is marked as valid with a valid icon even if you choose a framework from the list. In that case, the otherFramework field should be completely ignored.
In order to fix that, we can use the excluded option provided by the Excluded plugin as following:
FormValidation.formValidation(form, {
fields: {
framework: {
validators: {
notEmpty: {
message: 'Please select a framework',
},
},
},
otherFramework: {
validators: {
notEmpty: {
message: 'Please specific the framework',
},
},
},
},
plugins: {
excluded: new FormValidation.plugins.Excluded({
excluded: function (field, ele, eles) {
const selectedCheckbox = form.querySelector('[name="framework"]:checked');
const framework = selectedCheckbox ? selectedCheckbox.value : '';
return (field === 'otherFramework' && framework !== 'other') || (field === 'framework' && framework === 'other');
},
}),
},
});
When the field validation is ignored, its container will not have the success class, and the associated icon isn't shown
Excluding field by given condition