繁体   English   中英

Laravel 数组内的复杂验证规则

[英]Laravel Complex Validation Rule inside Array

我写了一个 API(Rest,JSON)并想验证传入的请求。

API 需要一个字段“Plan”。 在此字段中,客户有两个选择:“o2_Plan”或“telekom_Plan”。 其中之一是必需的。 所以我的验证看起来像:

'Plan.o2_Plan' => 'required_without:Plan.telekom_Plan|array',
'Plan.telekom_Plan' => 'required_without:Plan.o2_Plan',

这工作正常。 但计划中还有另一个条件规则:

'Plan.o2_Plan.tariff_variation_code' => 'required_without:Plan.o2_Plan.article_id|string',
'Plan.o2_Plan.article_id' => 'sometimes|required_without:Plan.o2_Plan.tariff_variation_code|string',

这意味着,您必须输入关税变化代码或文章 ID 或两者。

但是,如果客户端只传输 telekom_Plan(必须可能),则验证失败,并出现以下错误:

{
    "errors": {
        "Plan.o2_Plan.tariff_variation_code": [
            "The tariff_variation_code field is required when article_id is not present."
        ],
        "Plan.o2_Plan.article_id": [
            "The article_id field is required when tariff_variation_code is not present."
        ]
    }
} 

如果 o2_Plan 存在,我如何才能实现 o2_Plan 中的验证。

提前致谢。

最好的问候马丁

我有以下解决方案:

改变了

'Plan.o2_Plan' => 'required_without:Plan.telekom_Plan|array',

'Plan.o2_Plan' => ['required_without:Plan.telekom_Plan', 'array', new o2Plan(request('Plan.o2_Plan'))],

我的 o2Plan 规则 class 看起来像:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class o2Plan implements Rule
{
    protected $request;
    protected $message_text = '';

    /**
     * Create a new rule instance.
     *
     * @param array $request
     */
    public function __construct($request)
    {
        $this->request = $request;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ((!isset($this->request['tariff_variation_code']) || empty($this->request['tariff_variation_code']))
            &&
            (!isset($this->request['article_id']) || empty($this->request['article_id']))
        ) {
            $this->message_text = 'tariff_variation_code or article should not be empty';
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message_text;
    }
}

它工作正常:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM