仅显示我的输入数组的一条验证消息

Showing only one validation message for my array of inputs

我有一个包含 10 个输入字段的表单,我想检查这些输入字段中是否有任何一个为空。如果它们为空或超过 2 个字符,我只想显示一条错误消息。使用我当前的代码,我会为每个空字段显示一个错误。我不希望用户看到 10 条错误消息。我尝试了许多其他方法,但似乎没有用。

我希望错误消息显示: '预测不能为空或超过 2 个字符'

控制器

 public function store(Request $request) {
        $requestData = $request->get('match');
        $this->validate($request, [
            'match.*.homeTeam' => 'required|max:2',
            'match.*.awayTeam' => 'required|max:2'
        ]);
         try {
            collect($requestData)
                ->each(function ($match, $key) {
                    Prediction::create([
                        'user_id'  => auth()->id(),
                        'match_id' => $key,
                        'homeTeam' => $match['homeTeamName'],
                        'awayTeam' => $match['awayTeamName'],
                        'homeScore'=> $match['homeTeam'],
                        'awayScore'=> $match['awayTeam'],
                        'result'   => false
                    ]);
            });
            auth()->user()->participated = true; 
            auth()->user()->addPoint();
            auth()->user()->save();

            return redirect('/predictions')->with('success', 'Weekly prediction created, new predictions can be made every Tuesday!');

         } catch(\Exception $e) {
            return view('error.error');
         }   

    }

我的messages.blade.php文件

@if(count($errors) > 0)
@foreach($errors->all() as $error)
        <div class="alert alert-red">
            {{$error}}
        </div>
    @endforeach   
@endif

@if(session('success'))
    <div class="alert alert-green">
        {{session('success')}}
    </div>
@endif

@if(session('error'))
    <div class="alert alert-danger">
        {{session('error')}}
    </div>
@endif

风景

@include('inc.messages')
{!! Form::open(['method'=> 'POST', 'action'=>'PredictionController@store']) !!}
@foreach($matches as $match)
  <tr>
      <td> <small style="opacity: 0.5; font-size: 10px;">{{$match->date->formatLocalized('%d %B %Y')}} <small></td>
      <td>{{$match->date->format('H:i')}}</td>
          {{Form::hidden('match[' . $match->match_id . '][homeTeamName]', $match->homeTeam )}}
          {{Form::hidden('match[' . $match->match_id . '][status]', $match->status )}}
      <td>{{$match->homeTeam}}</td>
      <td>{{$match->awayTeam}}</td>
          {{Form::hidden('match[' . $match->match_id . '][awayTeamName]', $match->awayTeam )}}
      <td style="width: 150px !important;"><div>{{Form::number('match[' . $match->match_id . '][homeTeam]' , '', [ 'class' =>'form-control-sm col col-sm-3'])}} <span class="ml-2" style="color: white;">-</span> {{Form::number('match[' . $match->match_id . '][awayTeam]' , '', ['class' =>'form-control-sm col col-sm-3 ml-2'])}} </div></td>                      
 </tr>
@endforeach
{{Form::button('Submit', ['type' =>'submit', 'class' => 'submit-btn float-right mb-3'])}} 
{!! Form::close() !!}

有什么建议吗?

您可以检索给定键的 first 错误消息,如下所示:

foreach ($errors->first('match.*') as $message) {
    //
}

有关详细信息,请查看 Laravel 关于 Validation 的文档。

我想你可以这样做:

@if($errors)
    <div class="alert alert-red">
        {{ $errors->first() }}
    </div>  
@endif

如有错误,只显示第一个。

validate() 方法可以采用第三个参数指定自定义错误消息。

只显示一条针对任何验证失败的自定义错误消息。

你可以这样做:

    $this->validate(
         $request, 
         [ 
            'match.*.homeTeam' => 'required|max:2',
            'match.*.awayTeam' => 'required|max:2'
         ],
         ['match.*' => "Predictions can't be empty or have more than 2 characters"]);