Hiding success class and icon for optional field

FormValidation will not execute validators (except the notEmpty validator) when a field is empty. But the library still adds some CSS classes and icon to the field element and its container to let user know that the field is valid.
For example, if your form uses the Bootstrap plugin, the plugin will add .has-success or .has-danger class to the container element. It also adds .is-valid or .is-invalid class to the field element. If you want to remove the success class and feedback icon when a field is empty, then follow the next sections.

Hiding the success class

We can listen on the core.element.validated event as following:
const fv = FormValidation.formValidation(form, {
fields: {
...
},
plugins: {
...
},
})
.on('core.element.validated', function(e) {
// e.element presents the field element
// e.valid indicates the field is valid or not
// Get the validator options
const validators = fv.getFields()[e.field].validators;
// Check if the field has 'notEmpty' validator
if (validators && validators['notEmpty']
&& validators['notEmpty'].enabled !== false) {
return;
}
// Get the field value
const value = fv.getElementValue(e.field, e.element);
if (e.valid && value === '') {
// Now the field is empty and valid
// Remove the success color from the container
const container = FormValidation.utils.closest(e.element, '.has-success');
FormValidation.utils.classSet(container, {
'has-success': false
});
// Remove 'is-valid' class from the field element
FormValidation.utils.classSet(e.element, {
'is-valid': false
});
}
});

Hiding the valid icon

It's possible to get the icon element for a particular field element. First, we need to retrieve the Icon plugin instance via the getPlugin() method, and then get the icon for given element:
const fv = FormValidation.formValidation(form, {
fields: {
...
},
plugins: {
icon: new FormValidation.plugins.Icon({
...
}),
},
})
// Get the icon plugin instance
// fv is the FormValidation instance created above
// Assume that you're using the Icon plugin under the name 'icon'
const iconPlugin = fv.getPlugin('icon');
const iconElement = iconPlugin && iconPlugin.icons.has(e.element)
? iconPlugin.icons.get(e.element)
: null;
Inside the core.element.validated's event handler, we can hide the icon element when the field is valid and empty. Don't forget to show it when the field isn't valid or field isn't empty:
const iconPlugin = fv.getPlugin('icon');
const iconElement = iconPlugin && iconPlugin.icons.has(e.element)
? iconPlugin.icons.get(e.element)
: null;
// Get the field value
const value = fv.getElementValue(e.field, e.element);
if (e.valid && value === '') {
...
// Hide the icon
iconElement && (iconElement.style.display = 'none');
} else {
// Show the icon
iconElement && (iconElement.style.display = 'block');
}
Here is a demonstration for the steps above. The Middle name and Secondary email address fields are optional.
Hiding success class and icon for optional field

See also