php - 条件为 "or"的 Laravel 验证

标签 php laravel validation

我正在尝试在 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 Validation with or

Validation rules required_if with other condition (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值注入(inject)请求中的字段。

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

关于php - 条件为 "or"的 Laravel 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60302692/

相关文章:

PHP 帮助解释一个函数

php - Laravel和Vue-handler.call不是函数

php - PHP 中的正则表达式转义转义字符

Laravel 请求文件扩展名与提交的 Blob 不同

validation - Entity Framework IValidatableObject 引用 DbContext

php - 尝试从一个页面获取变量以将其重新填充到另一页面上

laravel - 如何在 laravel Blade 的图像 src 中使用 vue 变量?

php - Laravel ownsToMany 插入查询中的表顺序

javascript - jQuery Validate Remote - 检查电子邮件是否已经存在

php - 在 PHP 中验证选择下拉数组