php - 带有“或”条件的 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 的自定义验证规则,有条件地添加规则等等,还有这些帖子:
验证规则 required_if 与其他条件(Laravel 5.4)
但我似乎无法提出一个自定义规则,在该规则中我不查询整个表以了解名称是否存在(以防它不是“其他”)。这会使规则过于复杂,无法达到其目的。
我的另一个解决方案是在 user_organizations 表中添加一个名为“other”的条目,这并不理想。
我错过了什么吗?如何在没有复杂的自定义验证规则的情况下创建我想要的条件?
非常感谢。
解决方案
由于“其他”只是一个值而不是数据库中的记录,因此您可以简单地将其“扭曲”为以下内容:
'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
请求中的字段。
完成后,您将遵守允许您通过的“可空”选项。
推荐阅读
- mongodb - Mongoose:MongoError:>1 字段,同时尝试投影 $elemMatch
- c# - JIT SignalR Hub 发送和接收
- java - 如何将 HQL 放入实体中?
- image - rectifyStereoImages(图像校正)输出看起来失真
- ruby-on-rails - 由于 nil 值,Rails RSpec 功能测试失败,模型测试通过
- javascript - 通过拖放在输入中附加文件的问题
- android - React native Activity Indicator 仅在设备连接到笔记本电脑时有效
- c# - 添加脚本到游戏对象,找不到脚本
- ios - 通过 SKConstraint 使用 LERP 移动 SKCameraNode
- google-chrome-extension - 如何使用 Google Extension 选择从两个 DNS 服务器返回的 DNS A 记录,然后让 Chrome 连接到 A 记录 IP?