If one rule fails, do not test others after it.
Closed this issue · 2 comments
realjay007 commented
It would be nice to be able to configure the validator such that when a rule (from an array of rules) fail, the others below it (which may depend on previous rules) should not be tested.
For example, to validate user signup, you need to check if the email is a valid email. If it is then you check if the email has been used on the platform.
This might enhance performance by not running rules on data won't be used (because previous validation tests have failed).
realjay007 commented
I run validation by sending the rules as an array to mapFieldsRules.
Example below
// $valid_account, $card_exists_and_active and $user_owns_card are anonymous function variables
$config = array(
'account' => array(
array(
'required',
'message' => 'Please send account number'
),
array(
$valid_account,
'message' => 'Invalid account number format'
)
),
'amount' => array(
array(
'required',
'message' => 'Please send amount to transfer'
),
array(
'numeric',
'message' => 'Invalid amount'
)
),
'card_id' => array(
array(
'required',
'message' => 'Please send card ID'
),
array(
$card_exists_and_active,
'message' => 'There is an error with this card. I don\'t think it exists'
),
array(
$user_owns_card,
'message' => 'You have no right to use this card'
)
),
'remarks' => array(
array(
'optional'
)
)
);
$v = new Validator($_POST);
$v->mapFieldsRules($config);
$v->stopOnFirstFail(true); // Something like this to stop validation for any field if the first rule fails
if($v->validate()) {
// Do stuff
}
else {
// Send errors to user with one error message per field
}```