I have a form for creating a question with multiple(as many as one wishes) possible answers. Here is the picture:
The code for a single possible answer:
<div class="input-group">
{{-- Checkbox for the answer --}}
<span class="input-group-addon">
<input type="checkbox" name="answer[0][is_correct]" value="1">
</span>
{{-- Input field for the answer --}}
<input type="text" class="form-control" name="answer[0][body]">
{{-- . . . --}}
</div>
I need to validate that, there exist at least three answers for a question and at least one of them is correct. How can I achieve this?
I would consider separating your answer text fields from your answer checkboxes for the sake of clarity.
Below hasn't been tested - but something like the following should hopefully help you along?
$numAnswers = count($input->only('answers_text'));
$rules = [
'answers_checked' => 'array|min:1|max:' . $numAnswers,
'answers_text' => 'array|min:3|required',
'answers_text.*' => 'required|string',
];
$v = Validator::make($input, $rules);
if ($v->fails()) {
return response()->json($v->errors(), 422);
}
...