You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Livewire 2.12+Laravel10嵌套数组验证规则及错误信息配置

解决Livewire嵌套数组验证未生效问题

问题根源

你之前的验证规则失效,核心原因是未填写的问题对应的answers数组项不会被Livewire提交。比如有3个问题,用户只填了1个,answers数组只会包含1个元素,answers.*.choice规则仅对已存在的元素生效,缺失的项完全不会被验证。

解决方案步骤

1. 初始化answers数组

在组件的mount方法中,根据问题列表初始化answers,确保每个问题对应一个空的choice字段:

public $questions;
public $answers = [];

public function mount()
{
    // 示例:从数据库获取问题列表,替换成你的实际逻辑
    $this->questions = \App\Models\Question::all();
    
    // 为每个问题初始化空的choice项
    foreach ($this->questions as $question) {
        $this->answers[] = ['choice' => ''];
    }
}

2. 设置精准的验证规则

调整规则,确保answers数组长度与问题数量匹配,同时强制每个choice必填:

protected function rules()
{
    return [
        // 确保answers数组非空、是数组,且长度等于问题数量
        'answers' => ['required', 'array', 'size:' . count($this->questions)],
        // 每个choice字段必填,根据你的字段类型调整规则(比如integer如果是单选ID)
        'answers.*.choice' => ['required', 'string'],
    ];
}

3. 自定义错误信息

通过messages方法为每个问题设置针对性的错误提示:

protected function messages()
{
    $messages = [];
    
    // 为每个问题的choice字段生成自定义错误信息
    foreach ($this->questions as $index => $question) {
        $messages["answers.{$index}.choice.required"] = "请选择「{$question->title}」的答案";
    }
    
    // 数组长度不匹配时的提示
    $messages['answers.size'] = '请完成所有问题的作答';
    
    return $messages;
}

4. Blade视图绑定与错误展示

循环渲染时,绑定对应索引的choice字段,并显示对应问题的错误:

@foreach($questions as $index => $question)
    <div class="mb-4">
        <h4 class="font-medium">{{ $question->title }}</h4>
        <div class="mt-2">
            @foreach($question->options as $option)
                <label class="block mb-1">
                    <input type="radio" wire:model="answers.{{ $index }}.choice" value="{{ $option->id }}">
                    {{ $option->text }}
                </label>
            @endforeach
        </div>
        {{-- 显示当前问题的错误信息 --}}
        @error("answers.{$index}.choice")
            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
        @enderror
    </div>
@endforeach

<button wire:click="submit" class="px-4 py-2 bg-blue-600 text-white rounded">提交</button>

关键注意事项

  • 如果问题数量是动态生成的(比如从请求参数获取),务必在mount方法中先加载问题列表,再初始化answers数组,避免规则中的size值不准确。
  • 若使用复选框等多选项场景,可将choice改为数组类型,调整规则为answers.*.choice => ['required', 'array', 'min:1']。

内容的提问来源于stack exchange,提问作者Syaifudin Zuhri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 23:17:28