我的一个页面上有一个简单的多选答案表单。所有的字段都是必需的,我正在使用验证来检查它们是否全部完成和正确。
当我返回错误信息时,我不想说哪个答案是错的,我希望他们自己解决这个问题。但告诉他们哪一个具体的问题他们还没有填写是可以的。
鉴于此,我构建了这样的验证器:
$validator = Validator::make($request->all(), [
'multi1' => 'required|in:b',
'multi2' => 'required|in:a',
'multi3' => 'required|in:c',
'multi4' => 'required|in:b',
'multi5' => 'required|in:c',
'multi6' => 'required|in:a',
'multi7' => 'required|in:c',
'multi8' => 'required|in:c',
'multi9' => 'required|in:a',
'multi10' => 'required|in:b',
], [
'multi1.required' => 'The first question is empty!',
'multi2.required' => 'The second question is empty!',
'multi3.required' => 'The third question is empty!',
'multi4.required' => 'The fourth question is empty!',
'multi5.required' => 'The fifth question is empty!',
'multi6.required' => 'The sixth question is empty!',
'multi7.required' => 'The seventh question is empty!',
'multi8.required' => 'The eighth question is empty!',
'multi9.required' => 'The ninth question is empty!',
'multi10.required' => 'The tenth question is empty!',
'multi1.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi2.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi3.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi4.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi5.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi6.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi7.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi8.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi9.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
'multi10.in' => 'At least one of your answers was incorrect. Please review them and resubmit.',
]);
if ($validator->fails()) {
return redirect('/application/multichoice')
->withErrors($validator)
->withInput();
}
唯一的问题是,如果一个或多个问题不正确,则会多次重复相同的错误消息At least one of your answers was incorrect. Please review them and resubmit.
。
我把它打印在页面上,就像这样:
@if (count($errors) > 0)
<div class="alert alert-danger">
<p><b>There are some errors with your answers:</b></p>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
有没有一种简单的方法可以防止这种情况发生,或者只打印一次?
您可以跟踪以前的错误,并且只显示一个错误如果它与以前的错误不同:
@if (count($errors) > 0)
<div class="alert alert-danger">
<p><b>There are some errors with your answers:</b></p>
<ul>
{{--*/ $prev = null; /*--}}
@foreach ($errors->all() as $error)
@if ($prev != $error)
<li>{{ $error }}</li>
@endif
{{--*/ $prev = $error; /*--}}
@endforeach
</ul>
</div>
@endif