Laravel 数组项的条件验证规则

Laravel conditional validation rule for array items

我有以下工作验证规则,它检查以确保每个收件人、cc、bcc 电子邮件列表包含有效的电子邮件地址:

  return [
            'recipients.*' => 'email',
            'cc.*' => 'email',
            'bcc.*' => 'email',
        ];

我还需要能够允许字符串 ###EMAIL### 以及每个规则的电子邮件验证,并努力在 Laravel 5.8 中创建自定义验证规则(这不可能此时升级)。

知道怎么做吗?如果它是 Laravel 的更高版本,我正在考虑(未测试)让您了解我正在尝试做的事情:

return [
    'recipients.*' => 'exclude_if:recipients.*,###EMAIL###|email',
    'cc.*' => 'exclude_if:recipients.*,###EMAIL###|email',
    'bcc.*' => 'exclude_if:recipients.*,###EMAIL###|email',
];

在 5.8 中,您可以创建 Custom Rule Object让我们看看如何让它真正发挥作用。

  1. 使用 php artisan make:rule EmailRule
  2. 创建您的规则
  3. 让它看起来像这样
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class EmailRule implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($value === '###EMAIL###' or filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return true;
        }
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be valid email or ###EMAIL###.';
    }
}
  1. 包含在您的规则中,使其看起来像
return [
    'recipients.*' => [new EmailRule()],
    'cc.*' => [new EmailRule()],
    'bcc.*' => [new EmailRule()],
];
  1. 编写测试(可选)