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
const fv = FormValidation.formValidation(form, {
fields: {
...
},
plugins: {
...
},
})
.on('core.element.validated', function(e) {
const validators = fv.getFields()[e.field].validators;
if (validators && validators['notEmpty']
&& validators['notEmpty'].enabled !== false) {
return;
}
const value = fv.getElementValue(e.field, e.element);
if (e.valid && value === '') {
const container = FormValidation.utils.closest(e.element, '.has-success');
FormValidation.utils.classSet(container, {
'has-success': false
});
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({
...
}),
},
})
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;
const value = fv.getElementValue(e.field, e.element);
if (e.valid && value === '') {
...
iconElement && (iconElement.style.display = 'none');
} else {
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