php - 数组内的 Laravel 复杂验证规则
问题描述
我编写了一个 API(Rest,JSON)并想验证传入的请求。
API 需要一个“计划”字段。在此字段中,客户有两个选择:“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 规则类如下所示:
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;
}
}
它工作正常:-)
推荐阅读
- matplotlib - 如何在 jupyter notebook 中使用非衬线字体制作 matplotlib 绘图?
- python - 将 pandas DataFrame 列添加到行的最佳方法
- node.js - 使用来自 WebPack.DefinePlugin 的全局注入变量进行 NodeJS Mocha 单元测试
- r - 如何将参数列表传递给 facet_grid()
- reactjs - 是否可以使用 react-canvas-draw 设置背景图像?
- git - 如何在 git 中仅传输最新的 repo 更改文件?
- android - 你可以将 Flutter 项目导出到 Java 和 Swift 吗?
- asp.net - 我无法连接到使用从模型生成的实体框架创建的数据库实例
- python - TLS 证书验证失败
- python - Flask Post 错误 500(内部服务器错误)