Currently working on a personal project I was confronting a situation where I had to validate an attribute only if certain conditions where accomplished. The conditions where quite challenging and scenarios weren’t suitable, or maybe I didn’t know how they could be written in order to fulfill my validation requirements, as I had too many conditions to fulfill depending even on the value of certain attributes.
Background:
The attribute ‘A’ was required only if the form was of a certain type
The attribute ‘A’ supposed to be validated only if ‘B’ existed in the form and if ‘B’ fulfilled certain validation requirement. For example, if B existed and also if it had a value=‘EMAIL’, then ‘A’ was to be validated with ‘Email’ validation.
Conditional statements in Controllers should be avoided to keep their code clean and neat, so validators should handle them
My Solution:
a - ) I included attribute ‘A’ to be required at all times
b - ) Created a EConditionalValidator that will only execute a rule if certain validations are passed previously
array('account',
'application.components.validators.EConditionalValidator',
'conditionalRules' => array('B', 'compare', 'compareValue' => self::TYPE_EMAIL),
'rule' => array('A', 'email')
),
c - ) Then, depending on the type of FORM then I validate some attributes or anothers and then save the model without validating further its attributes:
if($_GET['FORM_TYPE'] == FORM_TYPE::TYPE_EMAIL)
$validationParams = array('A','D', 'C');
else
validationParams = array('account','A', 'D', 'F');
if ($model->validate($validationParams) && $model->save(false))
// success
else // failure
Final notes
I would like to know if anybody of you has confront a challenge like this with validation and what it was the solution.
EConditionalValidator is also capable of validating more than one condition before executing one. If its of any use for anyone of you, I would be more than happy to share it.