Laravel: validate an integer field that needs to be greater than another

前端 未结 8 2203
情歌与酒
情歌与酒 2020-11-27 15:08

I have two fields that are optional only if both aren\'t present:

$rules = [
  \'initial_page\' => \'required_with:end_page|integer|min:1|digits_between:          


        
8条回答
  •  自闭症患者
    2020-11-27 15:42

    If you're maintaining a project on Laravel 5.2 then the following should backport the current gt rule for you:

    class AppServiceProvider extends ServiceProvider
    {
      public function boot()
      {
        Validator::extend('gt', function($attribute, $value, $parameters, $validator) {
          $min_field = $parameters[0];
          $data = $validator->getData();
          $min_value = $data[$min_field];
          return $value > $min_value;
        });   
    
        Validator::replacer('gt', function($message, $attribute, $rule, $parameters) {
          return sprintf('%s must be greater than %s', $attribute, $parameters[0]);
        });
      }
    }
    

    You can then use it as per the current documentation:

    $rules = [
      'end_page' => 'gt:initial_page'
    ]; 
    

提交回复
热议问题