halkujabra
halkujabra

Reputation: 2942

laravel validation for checkboxes

How can I validate 'at least one of the two checkboxes in my form was checked'? I know other ways but I want to know if there is a validation rule for this in laravel?

Upvotes: 0

Views: 894

Answers (2)

Aurel
Aurel

Reputation: 3740

Yes, i think this is what you looking for:

$rules = array(
    'checkbox1' => 'required_without:checkbox2', //require if checkbox2 miss
    'checkbox2' => 'required_without:checkbox1', //require if checkbox1 miss
);

So if the two checkboxes are missed, validator will fail.

required_without:foo,bar,... The field under validation must be present only when any of the other specified fields are not present.

Doc

Upvotes: 2

The Alpha
The Alpha

Reputation: 146219

In Laravel, there is a way to require a check box field to be checked using accepted and what it does is that, the field under validation must be yes, on, or 1.

But you have different requirements and in this case you can add your custom rule using something like this:

// You may keep this code in your class before validation inside the method
Validator::extend('isOneChecked', function($attribute, $value, $parameters)
{
    return ($value || Input::has($parameters[0])) ? TRUE : FALSE;
});

Now you may use this rule for example, if one of your check box's name is checkbox1 and other one is checkbox2 then use something like this:

$rules = array (
    // other rules...
    'checkbox1' => 'isOneChecked:checkbox2',
);

Upvotes: 1

Related Questions