Reputation: 947
Recently I have faced a situation as follows:
There is a form with three inputs. All of them have related database properties (values). Now: at least one of them is required, but it can be any of them.
What could be the smartest way (preferably following Kohana and/or ORM's guidelines) to do so? I want this "rule" to be stored in model, not in controller.
So far I have managed to apply custom rule to all three fields, but this results in tripple error message, one for every field.
If more details are required - please let me know.
Upvotes: 2
Views: 807
Reputation: 937
Try this
public function rules(){
return array(
'field1' => array(
array('at_least', array($this, 1, array('field1', 'field2', 'field3'))),
),
'field2' => array(
array('at_least', array($this, 1, array('field1', 'field2', 'field3'))),
),
'field3' => array(
array('at_least', array($this, 1, array('field1', 'field2', 'field3'))),
),
);
}
public static function at_least($array, $needed = 1, $fields){
$found = 0;
foreach ($fields as $field){
if (isset($array[$field]) AND Valid::not_empty($array[$field])){
$found++;
}
}
return ($found >= $needed);
}
Upvotes: 1
Reputation: 3204
I think this is what you need
// File: application/classes/helper/validation.php
class Helper_Validation {
public static function one_not_empty($array, $keys)
{
if( ! is_array($keys))
{
// throw new Exception('Helper_Validation::one_not_empty expects an array');
return FALSE;
}
foreach($keys as $key)
{
// Change this IF to whatever is the required value
if(Arr::get($array, $key) !== NULL)
{
return TRUE;
}
}
return FALSE;
}
}
Now apply it to all fields:
$keys = array('field1', 'field2', 'field3');
$validation = Validation::factory($array)
->rule('field1', 'Helper_Validation::one_not_empty', array($keys))
->rule('field2', 'Helper_Validation::one_not_empty', array($keys))
->rule('field3', 'Helper_Validation::one_not_empty', array($keys));
I think this should work, have not tested though, let us know :)
Upvotes: 1