valitron icon indicating copy to clipboard operation
valitron copied to clipboard

RequiredWith

Open dikaso opened this issue 10 years ago • 4 comments

Title says it all.

How would you implement this?

dikaso avatar Jun 09 '14 11:06 dikaso

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.

vlucas avatar Jun 09 '14 15:06 vlucas

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.

dikaso avatar Jun 09 '14 19:06 dikaso

@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.

ellotheth avatar Jan 19 '15 00:01 ellotheth

https://github.com/vlucas/valitron/pull/267 should take care of this

mangopeaches avatar Oct 16 '18 02:10 mangopeaches