How add Custom Validation Rules when using Form Re

2019-01-21 04:24发布

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 is given below.I want to add custom validation numeric_array with field items.

  protected $rules = [
      'shipping_country' => ['max:60'],
      'items' => ['array|numericarray']
];

My cusotom function is given below

 Validator::extend('numericarray', function($attribute, $value, $parameters) {
            foreach ($value as $v) {
                if (!is_int($v)) {
                    return false;
                }
            }
            return true;
        });

How can use this validation method with about form request validation in laravel5?

8条回答
可以哭但决不认输i
2楼-- · 2019-01-21 04:49

All answers on this page will solve you the problem, but... But the only right way by the Laravel conventions is solution from Ganesh Karki

If you want to create validation by Laravel conventions follow this tutorial. It is easy and very well explained. It helped me a lot.

Tutorial link

查看更多
甜甜的少女心
3楼-- · 2019-01-21 04:50

You need to override getValidatorInstance method in your Request class, for example this way:

protected function getValidatorInstance()
{
    $validator = parent::getValidatorInstance();
    $validator->addImplicitExtension('numericarray', function($attribute, $value, $parameters) {
        foreach ($value as $v) {
            if (!is_int($v)) {
                return false;
            }
        }
        return true;
    });

    return $validator;
}
查看更多
登录 后发表回答