valitron
valitron copied to clipboard
RequiredWith
Title says it all.
How would you implement this?
Unfortunately, the title doesn't say it all. Required with what? Another field? A specific value? Please elaborate. A specific use-case would be appreciated.
Dummy example:
If i have field "type" with rule "in" allowing only 1 and 2.
I need another field to be required only if "type" field is 2.
We can see those examples in popular frameworks like laravel and symphony.
@DinkoMiletic probably means something like this:
protected function validateRequiredWith($field, $value, array $params) {
list($match, $child) = $params;
if ($value == $match) {
return array_key_exists($child, $this->_fields) && $this->validateRequired($child, $this->_fields[$child]);
}
return true;
}
When $value
is $match
, $child
is required.
$v = new Validator($post);
$v->rule('requiredWith', 'type', '2', 'second-field);
It'd be useful if you have a form field with multiple possible values (maybe a set of checkboxes), one of which requires extra information (maybe a text field has to be filled out if one of the checkboxes is selected).
The rest of the logic gets a little hinkey (e.g. hasRule()
, the initial validate()
check for required
, nested fields, etc.), but I think that's the gist.
https://github.com/vlucas/valitron/pull/267 should take care of this