Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation checkbox

I am using the laravel register function to register a user. I added a checkbox where the user needs to accept the terms and conditions. I only want the user to register when the checkbox is checked. Can I use the 'required' validation in laravel? This is my validation function:

 return Validator::make($data, [
        'firstName' => 'required|max:255',
        'lastName' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
        'checkbox' =>'required',
    ]);

When I use the function like this, laravel gives the required error for the checkbox even if it is checked.

This is the html of the checkbox

<input type="checkbox" name="checkbox" id="option" value="{{old('option')}}"><label for="option"><span></span> <p>Ik ga akkoord met de <a href="#">algemene voorwaarden</a></p></label>

I hope you guys can help me!

like image 511
Sander Van Keer Avatar asked May 20 '16 11:05

Sander Van Keer


4 Answers

Use the accepted rule.

The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

Sample for your case:

 return Validator::make($data, [
    'firstName' => 'required|max:255',
    'lastName' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|confirmed|min:6',
    'checkbox' =>'accepted'
]);
like image 58
SnakeDrak Avatar answered Nov 16 '22 21:11

SnakeDrak


It will work, just be sure the input value will not be an empty string or false. And 'checkbox' =>'required' is ok as long as the key is the value of the input name attribute.

like image 38
Calin Blaga Avatar answered Nov 16 '22 21:11

Calin Blaga


I just had a big frustration, because the code i'm using returns the checkbox value as a boolean value.

If you have a similar situation you can use the following rule:

[
 'checkbox_field' => 'required|in:1',
]
like image 4
Tschallacka Avatar answered Nov 16 '22 21:11

Tschallacka


Use required_without_all for checkbox :

return Validator::make($data, [
        'firstName' => 'required|max:255',
        'lastName' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
        'checkbox' =>'required_without_all',
    ]);

Refer : https://laravel.com/docs/5.1/validation#available-validation-rules

like image 3
Yasin Patel Avatar answered Nov 16 '22 23:11

Yasin Patel