2015-04-29 14 views
5

मेरे ajax स्क्रिप्ट इस तरह सरणी भेजें: यह सरणी Input::get('questions')मान्य सरणी Laravel 5

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

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

) 

के हैं एचटीएमएल हिस्सा उपयोगकर्ता में कई fields जोड़ सकते हैं।

क्या आप मेरी मदद कर सकते हैं के साथ मैं कुछ इस तरह की जरूरत है:

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

उत्तर

3

सरल: मान्य प्रत्येक question अलग से एक के लिए-प्रत्येक का उपयोग कर:

// 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 कस्टम सरणी के लिए मान्यता तत्वों

निम्न फ़ाइल खोलें

/resources/lang/en/validation.php 

तब कस्टम संदेश

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

जोड़ सकते हैं ताकि, अन्य फ़ाइल

/app/Providers/AppServiceProvider.php 

खोलने अब निम्नलिखित कोड का उपयोग करके बूट समारोह कोड के स्थान पर।

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

अब सरणी आवश्यक तत्व के लिए requiredarray उपयोग कर सकते हैं। और सरणी तत्व पूर्णांक प्रकार की जांच के लिए numericarray का भी उपयोग करें।

$this->validate($request, [ 
      'arrayName1' => 'requiredarray', 
      'arrayName2' => 'numericarray' 
     ]); 
संबंधित मुद्दे