欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

How to validate array in Laravel? post 表单数组验证 有大用 有大大用

I try to validate array POST in Laravel:

$validator = Validator::make($request->all(), [
            "name.*" => 'required|distinct|min:3',
            "amount.*" => 'required|integer|min:1',
            "description.*" => "required|string"

        ]);

I send empty POST and get this if ($validator->fails()) {} as False. It means that validation is true, but it is not.

How to validate array in Laravel? When I submit form with input name="name[]"



3 Answers 正确答案   


Asterisk symbol (*) means that you want to check VALUES in the array, not the actual array.

$validator = Validator::make($request->all(), [
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "Name" must be an array with at least 3 elements.

  • Values in the "name" array must be distinct (unique) strings, at least 3 characters long.


EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);


比如 form 中 <input type='text' name='first[name]' >


验证时  $data = $request->validate([

    "first"    => "required",
    "first.name"  => "required",
]);
validation.php 中 下面的验证方法不对 难道下短横有问题

'button0.wx_menu_name'
=>[
   
'required' => '菜单一上的菜单文字不能为空',
],

下面的验证方法是对的
'button0.*name'=>[    //或者干脆使用 button1.*来代替button0.*name吧
   'required' => '菜单一上的菜单文字不能为空',
],


I have this array as my request data from a HTML+Vue.js data grid/table:

[0] => Array
    (
        [item_id] => 1
        [item_no] => 3123
        [size] => 3e
    )
[1] => Array
    (
        [item_id] => 2
        [item_no] => 7688
        [size] => 5b
    )

And use this to validate which works properly:

$this->validate($request, [
    '*.item_id' => 'required|integer',
    '*.item_no' => 'required|integer',
    '*.size'    => 'required|max:191',
]);

You have to loop over the input array and add rules for each input as described here: Loop Over Rules

Here is a some code for ya:

$input = Request::all();
$rules = [];

foreach($input['name'] as $key => $val)
{
    $rules['name.'.$key] = 'required|distinct|min:3';
}

$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';

$validator = Validator::make($input, $rules);

//Now check validation:
if ($validator->fails()) 
{ 
  /* do something */ 
}

    来自  https://stackoverflow.com/questions/42258185/how-to-validate-array-in-laravel


    普通分类: