代码之家  ›  专栏  ›  技术社区  ›  SaidbakR

Laravel针对多个同名字段的自定义验证消息

  •  1
  • SaidbakR  · 技术社区  · 6 年前

    我在控制器的操作中进行了以下验证:

    foreach ($request['qtys'] as $key => $val){
                if (!$this->_validateMinQty($key, $job, $val)){
                    $customerTitle = $job->customers()->where('customer_id',$key)->first()->title;
                    return redirect()->back()->withErrors(['qtys' => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle])]);
                }
            }
    

    此检查多个表单的输入名为 qtys 他认为:

    @foreach($job->customers as $customer)
    
        <div class="form-group {{$errors->first('qtys has-error')}}">
            {!! Form::label('qtys-'.$customer->id, __('Qty').' '.$customer->title) !!}
            <div class="row">
                <div class="col-md-9">
                    {!! Form::text('qtys['.$customer->id.']',$customer->pivot->e_production,['class' =>'form-control qtys', "data-sumequal"=>"qty",'required' => 'required','title' => $customer->pivot->aid,'id' => 'qtys-'.$customer->id]) !!}
                    <div class="help-block with-errors"></div>
                     @php ($eleE =  $errors->first('qtys'))
                    @include('layouts.form-ele-error')
                </div>
                <div class="col-md-3">
                    <a href="/storage/create/{{$customer->pivot->aid}}" class="btn btn-nile"><i class="fox-add"></i>{{__('Add Storage')}}</a>
                </div>
            </div>
    
        </div>
        @endforeach
    

    上述代码有效,但有以下限制:

    在每个名为 qtys[x] 其中x是一个整数,仅为第一个输入 Testana 具有无效数量,如以下屏幕截图: enter image description here

    在控制器的操作返回消息中,我尝试对输入使用索引名称,如下所示:

    return redirect()->back()->withErrors(['qtys.10' => ....
    

    但是,它会阻止在任何情况下呈现错误消息 QTY 领域有什么解决办法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   SaidbakR    6 年前

    我找到的解决方案是从 definition of first method 可在视图中找到:

    @php ($eleE =  $errors->first('qtys'))
    

    在我的代码中,这应该更改为:

    @php ($eleE =  $errors->first('qtys.'.$customer->id))
    

    因为多个字段得到的密钥等于客户id。 这是我通常使用的一种技术,当我想在单个帖子或单个表单元素中发送两段数据时。 然后在控制器中,我保持第一次尝试,

    return redirect()->back()->withErrors(['qtys.'.$key => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle])]);
    

    哪里 $key 是一个整数。