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

前端 未结 9 1123
情歌与酒
情歌与酒 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

    You don't need to extend the validator to validate array items, you can validate each item of a array with "*" as you can see in Array Validation

    protected $rules = [
          'shipping_country' => ['max:60'],
          'items' => ['array'],
          'items.*' => 'integer'
    ];
    
    0 讨论(0)
  • 2020-12-07 13:22

    Using Validator::extend() like you do is actually perfectly fine you just need to put that in a Service Provider like this:

    <?php namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    
    class ValidatorServiceProvider extends ServiceProvider {
    
        public function boot()
        {
            $this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
            {
                foreach ($value as $v) {
                    if (!is_int($v)) {
                        return false;
                    }
                }
                return true;
            });
        }
    
        public function register()
        {
            //
        }
    }
    

    Then register the provider by adding it to the list in config/app.php:

    'providers' => [
        // Other Service Providers
    
        'App\Providers\ValidatorServiceProvider',
    ],
    

    You now can use the numericarray validation rule everywhere you want

    0 讨论(0)
  • 2020-12-07 13:23

    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;
    }
    
    0 讨论(0)
提交回复
热议问题