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

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

    Custom Rule Object

    One way to do it is by using Custom Rule Object, this way you can define as many rule as you want without need to make changes in Providers and in controller/service to set new rules.

    php artisan make:rule NumericArray
    

    In NumericArray.php

    namespace App\Rules;
    class NumericArray implements Rule
    {
       public function passes($attribute, $value)
       {
         foreach ($value as $v) {
           if (!is_int($v)) {
             return false;
           }
         }
         return true;
       }
    
    
      public function message()
      {
         return 'error message...';
      }
    }
    

    Then in Form request have

    use App\Rules\NumericArray;
    .
    .
    protected $rules = [
          'shipping_country' => ['max:60'],
          'items' => ['array', new NumericArray]
    ];
    

提交回复
热议问题