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: {
enabled: true,
country: 'BR',
message: 'Please enter a valid Brazilian ID number',
},
vat: {
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) {
case 14:
fv
.disableValidator('yourId', 'id')
.enableValidator('yourId', 'vat')
.revalidateField('yourId');
break;
case 11:
default:
fv.enableValidator('yourId', 'id').disableValidator('yourId', 'vat').revalidateField('yourId');
break;
}
});
Switching validators on the same field
See also