Switching validators on the same field

In general, a field might have different validators. Based on various conditions, some of them can be turned on, and the remaining are turned off.
For example, the following form asks user to fill in a number which must be a valid Brazilian id validator (known as CPF), or vat validator (known as CNPJ) number. CPF and CNPJ numbers have 11 and 14 characters respectively. Based on the length of input, we can guess which type of number user is trying to put in.
Firstly, use the enabled option to enable (disable) validators initially
const form = document.getElementById('demoForm');
const fv = FormValidation.formValidation(form, {
fields: {
yourId: {
validators: {
id: {
// The id validator is enabled by default
enabled: true,
country: 'BR',
message: 'Please enter a valid Brazilian ID number',
},
vat: {
// The vat validator is disabled initially
enabled: false,
country: 'BR',
message: 'Please enter a valid Brazilian VAT number',
},
},
},
},
});
Lastly, turn on (off) the validators based on the length of field:
form.querySelector('[name="yourId"]').addEventListener('keyup', function (e) {
switch (e.target.value.length) {
// User is trying to put a VAT number
case 14:
fv
// Disable the id validator
.disableValidator('yourId', 'id')
// Enable the vat one
.enableValidator('yourId', 'vat')
// Revalidate field
.revalidateField('yourId');
break;
// User is trying to put an ID number
case 11:
default:
fv.enableValidator('yourId', 'id').disableValidator('yourId', 'vat').revalidateField('yourId');
break;
}
});
Switching validators on the same field

See also