Conditional validation
← ejemplos
There is a common case that a field validator rules depend on additional conditions. For example, when you stop using a software or an online service, you might be asked for the reason.
You can pick one from the given list, or choose a kind of "Other" checkbox. In the case that checkbox is selected, you have to indicate the specific reason. The reason is only required if you don't choose given one.
This example suggests two approaches that you can use for dealing with these kind of conditional validation.
Using callback validator
The first solution is to use the callback validator.
The callback
function simply ignores validation logic and returns
true
if the conditions don't happen. Otherwise, perform your specific logic
to check the field validity.
One more thing, even when the field validation is ignored, the plugin still adds the success class to the container as well as shows the tick icon.
In this case, you can trigger the event to mark the field as ignored. This trick is described in the Hiding success class example.
Enabling validators when meeting conditions
The second solution uses the enabled option and enableFieldValidators() method.
Initially, the field validators are disabled by setting enabled: false
:
Later, when conditions happen, these validators can be turned on (off) by calling the
enableFieldValidators()
method: