How add Custom Validation Rules when using Form Request Validation in Laravel 5

前端 未结 9 1152
情歌与酒
情歌与酒 2020-12-07 12:31

I am using form request validation method for validating request in laravel 5.I would like to add my own validation rule with form request validation method.My request class

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 13:21

    The accepted answer works for global validation rules, but many times you will be validating certain conditions that are very specific to a form. Here's what I recommend in those circumstances (that seems to be somewhat intended from Laravel source code at line 75 of FormRequest.php):

    Add a validator method to the parent Request your requests will extend:

    input(), $this->rules(), $this->messages(), $this->attributes());
    
            if(method_exists($this, 'moreValidation')){
                $this->moreValidation($v);
            }
    
            return $v;
        }
    }
    

    Now all your specific requests will look like this:

     'max:60',
                'items' => 'array'
            ];
        }
    
        // Here we can do more with the validation instance...
        public function moreValidation($validator){
    
            // Use an "after validation hook" (see laravel docs)
            $validator->after(function($validator)
            {
                // Check to see if valid numeric array
                foreach ($this->input('items') as $item) {
                    if (!is_int($item)) {
                        $validator->errors()->add('items', 'Items should all be numeric');
                        break;
                    }
                }
            });
        }
    
        // Bonus: I also like to take care of any custom messages here
        public function messages(){
            return [
                'shipping_country.max' => 'Whoa! Easy there on shipping char. count!'
            ];
        }
    }
    

提交回复
热议问题