Validate array Laravel 5

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

My ajax script send array like this: This array belong to Input::get('questions')

 Array (     [0] => Array         (             [name] => fields[]             [value] => test1         )      [1] => Array         (             [name] => fields[]             [value] => test2         )  ) 

In html part user can add multiple fields.

Could you help me with I need something like this:

           $inputs = array(                 'fields'    => Input::get('questions')             );              $rules = array(                 'fields'    => 'required'             );             $validator = Validator::make($inputs,$rules);                  if($validator -> fails()){                     print_r($validator -> messages() ->all());                 }else{                     return 'success';                 } 

回答1:

Simple: validate each question separately using a for-each:

// First, your 'question' input var is already an array, so just get it $questions = Input::get('questions');  // Define the rules for *each* question $rules = [     'fields' => 'required' ];  // Iterate and validate each question foreach ($questions as $question) {     $validator = Validator::make( $question, $rules );      if ($validator->fails()) return $validator->messages()->all(); }  return 'success'; 


回答2:

Laravel Custom Validation for Array Elements

Open the following file

/resources/lang/en/validation.php 

Then custom message add

'numericarray'         => 'The :attribute must be numeric array value.', 'requiredarray'        => 'The :attribute must required all element.', 

So that, open the another file

/app/Providers/AppServiceProvider.php 

Now replace the boot function code by using following code.

public function boot() {     // it is for integer type array checking.     $this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)     {         foreach ($value as $v) {             if (!is_int($v)) {                 return false;             }         }         return true;     });     // it is for integer type element required.    $this->app['validator']->extend('requiredarray', function ($attribute, $value, $parameters)     {         foreach ($value as $v) {             if(empty($v)){                 return false;             }         }         return true;     }); } 

Now can use requiredarray for array element required. And also use the numericarray for array element integer type checking.

$this->validate($request, [             'arrayName1' => 'requiredarray',             'arrayName2' => 'numericarray'         ]); 


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