Laravel 4: validate checkbox at least one

蹲街弑〆低调 提交于 2019-12-21 20:47:16

问题


I need to validate checkbox array:

<input name="cats[]" type="checkbox" value="1"> sport
<input name="cats[]" type="checkbox" value="2"> music
<input name="cats[]" type="checkbox" value="3"> business

I found "array" validation in documentation:

Validator::make( 
    [ 'cats' => Input::get('cats') ],
    [ 'cats' => 'array' ]
);

Is there any built-in way to check if at least one item checked? Also, how to check if values submitted match a given list?


回答1:


You can use min:value to validate a numeric value and you can also use it to validate an array's size.

Validator::make( 
    [ 'cats' => Input::get('cats') ],
    [ 'cats' => 'min:1' ]
);

Examples:

$validator = Validator::make([
    'cats' => ['Boots', 'Mittens', 'Snowball']
    ], ['cats' => 'min: 1']);

$result = $validator->fails(); // returns false

$validator = Validator::make([
    'cats' => ['Boots', 'Mittens', 'Snowball']
    ], ['cats' => 'min: 2']);

$result = $validator->fails(); // returns false

$validator = Validator::make([
    'cats' => ['Boots', 'Mittens', 'Snowball']
    ], ['cats' => 'min: 4']);

$result = $validator->fails(); // returns true



回答2:


As of laravel 5 you can just add required rule

<input name="cats[]" type="checkbox" value="1"> sport
<input name="cats[]" type="checkbox" value="2"> music
<input name="cats[]" type="checkbox" value="3"> business

// Controller
$rules = $this->validate($request, array('cats'=>'required'));
// will do the work



回答3:


If you don't mind touching your input data, you could do:

$data = Input::all();
$data['cats'] = Input::has('cats') ? implode(',',$data['cats']) : null;
$rules = [ 'cats' => 'required|in:foo,bar' ];
$validator = Validator::make($data, $rules);



回答4:


Bit late to this party but surely just making it "required" will suffice?

public function rules(){
    return [
        'checkboxarray' => 'required'
    ];
}


来源:https://stackoverflow.com/questions/23880126/laravel-4-validate-checkbox-at-least-one

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