4

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?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
mwafi
  • 3,946
  • 8
  • 56
  • 83

4 Answers4

9

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
Sumeet
  • 1,683
  • 20
  • 27
7

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
Maury
  • 610
  • 5
  • 7
  • no "min" validate only length of text, not length of array, (tested not working) – mwafi May 27 '14 at 02:38
  • where in Laravel API (you found that "min" can validate array size)? please provide link? – mwafi May 27 '14 at 03:02
  • I have not seen it in the documentation. I didn't know this was possible until today. I looked at [Validator.php](https://github.com/laravel/framework/blob/master/src/Illuminate/Validation/Validator.php) - and if you look at the getSize function, you will see that it does in fact validate arrays by their size. – Maury May 27 '14 at 03:13
2

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);
Greg
  • 365
  • 1
  • 3
  • 12
2

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

public function rules(){
    return [
        'checkboxarray' => 'required'
    ];
}
ggdx
  • 3,024
  • 4
  • 32
  • 48