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

时间:2018-11-10 14:11:30

标签: php laravel laravel-validation

我有一个包含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() !!}

有什么提示吗?

3 个答案:

答案 0 :(得分:2)

我认为您可以执行以下操作:

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

如果有错误,请仅显示第一个。

答案 1 :(得分:0)

您可以按如下方式检索给定密钥的first错误消息:

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

有关更多信息,请参阅Validation上的Laravel文档。

答案 2 :(得分:0)

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"]);