CakePHP Validation - isUnique OR inList
(New to CakePHP, so this may be an obvious thing, but I was unable to find a solution after searching for a couple of hours - the ambiguous nature of "or开发者_运维百科", I guess...)
I am trying to modify an existing CakePHP validation rule, which uses the isUnique
rule, so that it will validate for values which satisfy either the isUnique
rule or an inList
rule.
The previous code:
'isUnique' => array(
'rule' => 'isUnique' ,
'message' => "We're sorry, but this QA number is already being used.",
'last' => TRUE,
),
My (faulty) code:
'isUnique' => array(
'rule' => array(
'isUnique' ,
array( 'inList' , array( '111213' , '141516' , '171819' , '202122' ) )
) ,
'message' => "We're sorry, but this number is already being used.",
'last' => TRUE,
),
So, (as simple as this may be), how can you string CakePHP validation rules together with an "OR" logical operator? I can see that you can apply a cascade of "AND" rules (with each testing for a specific issue and, if failing that test, rejecting the value), but "OR" rules have me scratching my head...
Any help appreciated.
You'll have to make that a custom validation rule. Add this in your model:
public function isUniqueOrInList(array $data, array $list) {
return in_array(current($data), $list) || $this->isUnique($data);
}
Then declare your rule like:
'rule' => array('isUniqueOrInList', array('111213', '141516', '171819', '202122'))
精彩评论