2015-04-29 30 views
5

script ajax của tôi gửi cho mảng như thế này: mảng này thuộc về Input::get('questions')Validate mảng Laravel 5

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

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

) 

Trong html sử dụng một phần có thể thêm nhiều fields.

Ông có thể giúp tôi với tôi cần một cái gì đó như thế này:

  $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'; 
       } 

Trả lời

3

đơn giản: xác nhận mỗi question riêng sử dụng một 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'; 
0

Laravel Tuỳ chỉnh Validation cho mảng Elements

Mở tệp sau

/resources/lang/en/validation.php 

Sau đó thông báo tùy chỉnh thêm

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

Vì vậy mà, mở một tập tin

/app/Providers/AppServiceProvider.php 

Bây giờ thay thế mã chức năng khởi động bằng cách sử dụng đoạn mã sau.

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; 
    }); 
} 

Bây giờ có thể sử dụng requiredarray cho các phần tử mảng được yêu cầu. Và cũng có thể sử dụng số numericarray để kiểm tra loại số nguyên tố mảng.

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