Reputation: 900
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!
Upvotes: 55
Views: 108933
Reputation: 11
public function store(Request $request)
{
$datos=$request->validate([
'name' =>'required|max:60',
'descrip' =>'nullable|max:255',
'finish' =>'nullable', //this is the checkbox
'urgent' =>'required|numeric|min:0|max:2',
'limit' =>'required|date-format:Y-m-d\TH:i'
]);
if(isset($datos['finish'])){
if ($datos['finish']=="on"){
$datos['finish']=1;
}
}else{
$datos['finish']=0;
}
$tarea=Tarea::create($datos);
return redirect()->route('tarea.index');
}
Upvotes: 1
Reputation: 3642
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'
]);
Upvotes: 141
Reputation: 28722
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',
]
Upvotes: 6
Reputation: 1373
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.
Upvotes: 8
Reputation: 5731
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
Upvotes: 4