首页 > 解决方案 > 带有“或”条件的 Laravel 验证

问题描述

我正在尝试在 Laravel 中使用有点复杂的“或”条件进行输入验证。

我需要验证器来验证输入(让它通过),如果它的值存在于特定表中或者它的值是“其他”。

到目前为止,我有:

$validator = Validator::make($data, [

    ...

    'doc_organization' => ['required_with:rb_regist,doctor, exists:user_organizations,full_name'], // TODO: must exist in user_organizations table or be "other"
    'doc_custom_organization' => ['required_if:doc_organization,other', 'max:160'],

    ...

我看了一下 Laravel 的自定义验证规则,有条件地添加规则等等,还有这些帖子:

Laravel 验证或

验证规则 required_if 与其他条件(Laravel 5.4)

但我似乎无法提出一个自定义规则,在该规则中我不查询整个表以了解名称是否存在(以防它不是“其他”)。这会使规则过于复杂,无法达到其目的。

我的另一个解决方案是在 user_organizations 表中添加一个名为“other”的条目,这并不理想。

我错过了什么吗?如何在没有复杂的自定义验证规则的情况下创建我想要的条件?

非常感谢。

标签: phplaravelvalidation

解决方案


由于“其他”只是一个值而不是数据库中的记录,因此您可以简单地将其“扭曲”为以下内容:

'doc_organization' => ['nullable|required_with:rb_regist,doctor, exists:user_organizations,full_name'],

扭曲的是,在您之前,您Validator可以简单地检查您请求的值,例如:

if($request->doc_organization == "other"){
  $request->merge(['doc_organization' => null]);
}

并将值注入null请求中的字段。

完成后,您将遵守允许您通过的“可空”选项。


推荐阅读