Laravel validation checkbox

做~自己de王妃 提交于 2019-12-20 17:38:15

问题


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 to 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!


回答1:


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.




回答2:


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'
]);



回答3:


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',
]



回答4:


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




回答5:


Your validation rules must corrolate with the name attributes of your html form fields:

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


来源:https://stackoverflow.com/questions/37345363/laravel-validation-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!