验证不同的测验输入(文本区域和广播)



我有多个测验,每个测验由多个问题组成,每个问题可以是(MCQ,真或假或自由文本)。

questions_types:

id | type
1  | MCQ
2  | True or false
3  | Text

问题:

id | question_en | question_fr | type_id
1  | question 1  | question 1  | 1
2  | question 2  | question 2  | 2
3  | question 3  | question 3  | 3

答案:

id | answer_en | answer_fr  | question_id
1  | answer 1  | répondre 1 | 1
2  | answer 2  | répondre 2 | 1
3  | answer 3  | répondre 3 | 1
4  | true      | vrai       | 2
5  | false     | faux       | 2

测试刀片:

@foreach($questions as $question)
<h4>{{ $question->question_en }}</h4>
@if($question->type_id != 3)
@foreach($question->answers as $answer)
<input type="radio" name="answers[{{ $question->id }}]" value="{{ $answer->answer_en }}" @if(old("answers." . $question->id) == $answer->answer_en) checked="checked" @endif>
@endforeach
@else
<textarea name="answers[{{ $question->id }}]">{{ old("answers." . $question->id) }}</textarea>
@endif
@endforeach

输出:

<h4>question 1</h4>
<input type="radio" name="answers[1]" value="answer 1">
<input type="radio" name="answers[1]" value="answer 2">
<input type="radio" name="answers[1]" value="answer 3">
<h4>question 2</h4>
<input type="radio" name="answers[2]" value="true">
<input type="radio" name="answers[2]" value="false">
<h4>question 3</h4>
<textarea name="answers[3]"></textarea>

表单请求验证:

public function rules()
{
return [
'answers' => 'required|array',
'answers.*' => 'required',
];
}

但是它只验证textarea。即使没有检查无线电,它也会通过。所有收音机都必须加满油。这是动态的,所以我不能指定要验证的计数或值。如何确保所有无线电输入都被检查了?

当没有选择单选按钮时,请求即使作为空值也不包含该单选按钮。

换句话说,如果你没有选择任何单选按钮,请求是这样的:

"answers" => array:2 [▼
3 => "hi"
]

所以'answers.*' => 'required',没有任何意义。

你可以选择一个单选作为默认值,但我认为这不是一个很好的方式来测试。您可以为每个单选按钮添加一个隐藏输入:

@foreach($questions as $question)
<h4>{{ $question->question_en }}</h4>
@if($question->type_id != 3)
@foreach($question->answers as $answer)
<input type="hidden" name="answers[{{ $question->id }}]" value="">
<input type="radio" name="answers[{{ $question->id }}]" value="{{ $answer->answer_en }}" @if(old("answers." . $question->id) == $answer->answer_en) checked="checked" @endif>
@endforeach
@else
<textarea name="answers[{{ $question->id }}]">{{ old("answers." . $question->id) }}</textarea>
@endif
@endforeach

所以通过这种方式,单选按钮将被发送,即使没有值,也将被验证

最新更新