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!
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'
]);
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.
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',
]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With