Is there a simple method to go about setting a X out of Y validator?
Suppose there are 5 fields, and only 1 is required, doesn’t matter which one; or maybe 2 of them.
Is there a simple method to go about setting a X out of Y validator?
Suppose there are 5 fields, and only 1 is required, doesn’t matter which one; or maybe 2 of them.
Yes, you can do that easy by writing validator method inside model class(or eventually write new validation class).
However because function definition, you need to provide attribute name, but nothing stop you to validate if one or two of attributes are set or not.
public function atMinimum($attribute, $params) {
if (is_array($params)) {
$fields = explode(', ', $params[0]);
$min = $params['count'];
} else {
$fields = explode(', ', $params);
$min = 1;
}
$count = 0;
foreach ($fields as $name) {
if ( !empty($this->$name) ) { $count++; }
echo $this->$name;
}
echo $count;
if ($count < $min) {
$this->addError($attribute, 'Must select at least one of these: '.implode(', ', $fields) );
}
}
I suppose it could easily be adapted to check max. So fill 2 or 3 out of these 5.
I’m just using it for username and email address.
I see that you’ve already solved this problem with your own custom validators. But for other readers facing the same problem, this validator (atleastvalidator)might be useful.