【问题标题】:Laravel custom validation rule that works with not required empty fieldLaravel 自定义验证规则,适用于不需要的空字段
【发布时间】:2018-09-11 05:23:41
【问题描述】:

我需要文件字段,该字段作为路径记录在数据库中。如果数据库中的字段为空,我想将其设为可选。在我的控制器的 update 操作中,我设置了以下验证:

$this->validate(request(),[
    'drawings' => 'requiredIfEmpty:'.$product->drawings.'|file|max:'. config('fox.photoMaxSize').'|mimes:pdf',

然后在app/Providers/AppServiceProvider.php我定义了requiredIfEmpty验证器:

Validator::extend('requiredIfEmpty',function ($attribute,$value,$parameters,$validator){
        if(is_null($parameters[0]) || empty($parameters[0])){
            if (is_null($value)){
                return false;
            }
        }
        return true;
    });

    Validator::replacer('requiredIfEmpty', function ($message, $attribute, $rule, $parameters) {
        return __('The :attr is required',['attr' => $attribute]);
    });

_form 视图中,我在drawings 字段中使用 表单助手,如下所示:

<div class="form-group {{$errors->first('drawings','has-error')}}">
    @if (!is_null($product->drawings))
    <a href="{{$product->drawings}}" target="_bfox"><img src="/imgs/pdf.png" alt="{{__('PDF File')}}" title="{{__('PDF File')}}" /></a>
    <br>
    @else
    <img src="/imgs/empty.png" width="64" height="64" alt="{{__('Empty')}}..." title="{{__('Empty')}}..." /> <br>
    @endif
    {!! Form::label('drawings', __('Drawings')) !!}        

        {!! Form::file('drawings',['class' => 'btn btn-info','title' =>__('PDF file')]); !!}
        @php ($eleE =  $errors->first('drawings'))
        @include('layouts.form-ele-error')

</div>

问题是,我的自定义验证规则没有被调用,因为该字段不是必需的并且它具有空值。我需要任何允许这两种情况的方法:

  1. drawings文件字段为空且$product-&gt;drawings不为空时,不进行验证
  2. drawings 文件字段为空且$product-&gt;drawings 为空时,将进行验证。

换句话说,我需要一个像requiredIf 这样的内置验证规则,但它不采用另一个表单字段作为参数,它只是采用另一个值,即使是表单字段值也始终有效为空且该字段不是必需的。

【问题讨论】:

    标签: laravelcollective php laravel laravel-5


    【解决方案1】:

    当规则的值为空时,您应该使用extendImplicit 函数来运行规则。

    Validator::extendImplicit('required_if_exists', function($attribute, $value, $parameters, $validator) {
        //
    });
    

    或者,在 Rule 类中,您应该实现 ImplicitRule 接口而不是 Rule

    use Illuminate\Contracts\Validation\ImplicitRule;
    
    class RequiredIfExists implements ImplicitRule {
        //
    }
    

    【讨论】:

      【解决方案2】:

      我找到了一个与 Laravel 验证没有直接关系的解决方案。这将取决于保留文件字段的原始验证并使其不需要,然后在控制器的操作中创建验证逻辑,如果发现错误则返回错误包消息。解决方案类似于以下 sn-p:

      public function update(Request $request, Product $product)
          {       
              $product = Product::find(request('product'));
              $this->validate(request(),[
      
                  'drawings' => 'file|max:'. config('fox.photoMaxSize').'|mimes:pdf' //Original validation
      
              ]);
      if(is_null($request->drawings) && is_null($product->drawings)){
                  return redirect()->back()->withErrors(['drawings' => __('A drawing file must be specified')]);
              } //If the field is null and the database attribute is null too an error message is returned to form's file field.
      ...
      }
      

      但是,这个解决方案没有回答我们如何定义一个始终调用的自定义验证规则,而该字段是否设置为必需?

      Reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-07
        • 2021-07-20
        • 2019-05-18
        • 2017-04-11
        • 2018-02-18
        • 2016-12-18
        相关资源
        最近更新 更多