Search code examples
phplaravellaravel-5laravel-5.3

How can we do custom validation for multi dimensional array in laravel 5.3


I am using a 2 dimensional array of fields in Laravel 5.3. I wish to validate all the values of that as required and to display the individual error messages. I used the validation in the controller function as follows

$this->validate($request, [
            'training_id' =>'required',            
            'survey_name' =>'required',  
            'question.*' =>'required',
            'answer_option.*.*' =>'required'
        ],
        ['question.*.required' => 'The question field is required.',
        'answer_option.*.*.required' => 'The answer field is required.']);

In the view page while i tried to display all the error messages, only the first row of answers will be validated and the others won't. The error messages are as

Array ( [0] => The question field is required. [1] => The question field is required. [2] => The answer_option.0.0 field is required. [3] => The answer_option.0.1 field is required. [4] => The answer_option.0.2 field is required. [5] => The answer_option.0.3 field is required. [6] => The training id field is required. [7] => The survey name field is required. ) 

Solution

  • To Validate all the fields with custom error message individually, Creating validator manually is the best solution....

    step-1:

    use Validator; (after namespace of any controller where validation is needed)
    

    step-2:

    Add a method (suppose the method name check_data()). And inside the following code will be placed....

    public function check_data(Request $request){
    
        //Rules for form fields
        $rules = array(
            'training_id' =>'required',
            'survey_name' =>'required',
            'question' =>'required',
            'answer_option' =>'required'
        );
    
        //Custom message for individual fields
        $messages = array(
            'training_id.required' => 'Training Id should not be empty...',
            'survey_name.required' => 'Survey Name  is Essential...',
            'question.required' => 'Question is urgent...',
            'answer_option.required' => 'Answer option can be any one but required...'
    
        );
    
        $validator = Validator::make($request->all(), $rules, $messages);
    
        //Check for validation
        if ($validator->fails()) {
            //if validation fails
            return redirect()->back()->withInput()->withErrors($validator);
        } else {
            //Validation is successful and do as you wish
            return "All data are validated !!";
    
        }
    
    
    
    
    }
    

    Hopefully, It will work