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

如何验证数组含特定值?实现关联字段必填的自定义验证规则

问题描述

假设有一个模型的数组属性为整数类型,示例如下:

[1, 2, 3, 4]

我希望当该数组包含特定值(如1)时,另一个字段为必填项,现有验证规则如下:

'record.status.*' => new EnumRule(Status::class),
'record.status_other' => ['required_if:record.status', 'contains the value 1'],

请问如何创建contains the value 1对应的验证规则?

解决方案

你可以通过两种方式实现这个验证逻辑:

方式一:用闭包直接编写自定义判断

不需要额外创建规则类,直接在验证规则里用闭包实现逻辑,适合一次性使用:

'record.status_other' => [
    function ($attribute, $value, $fail) {
        $statusArray = request()->input('record.status');
        // 当状态数组存在且包含1,同时当前字段为空时触发验证失败
        if (is_array($statusArray) && in_array(1, $statusArray) && empty($value)) {
            $fail('当状态包含1时,status_other字段为必填项');
        }
    },
],

方式二:创建可复用的自定义验证规则类

如果这个验证逻辑需要在多个地方使用,可以生成自定义规则类:

  1. 生成规则文件:
php artisan make:rule ArrayRequiresField
  1. 在app/Rules/ArrayRequiresField.php中编写逻辑:
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ArrayRequiresField implements Rule
{
    protected $targetArray;
    protected $targetValue;

    public function __construct(string $targetArray, int $targetValue)
    {
        $this->targetArray = $targetArray;
        $this->targetValue = $targetValue;
    }

    public function passes($attribute, $value)
    {
        $arrayData = request()->input($this->targetArray);
        // 数组包含目标值但当前字段为空时,验证不通过
        return !(is_array($arrayData) && in_array($this->targetValue, $arrayData) && empty($value));
    }

    public function message()
    {
        return "当{$this->targetArray}包含值{$this->targetValue}时,此字段为必填项";
    }
}
  1. 在验证规则中调用:
'record.status_other' => [new \App\Rules\ArrayRequiresField('record.status', 1)],

补充说明

  • 闭包方式代码更简洁,适合单次场景;
  • 自定义规则类可复用性更强,适合多场景重复使用的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:30:54