【问题标题】:Laravel validate the field on the basis of value of another fieldLaravel 根据另一个字段的值验证该字段
【发布时间】:2018-09-04 08:40:59
【问题描述】:

我想验证两个字段,即“类型”和“选项”,其中“类型”字段是枚举。只有当 'type' 字段的值为 'opt' 时,才应验证 'options' 字段。

$this->validate($request, [
    'type' => 'required|in:opt,number,text,file,image',
    'options'=>the condition I need(if type is 'opt')
]);

【问题讨论】:

    标签: php laravel validation


    【解决方案1】:

    您可以像这样有条件地添加验证

    $this->validate($request, [
            'type' => 'required|in:opt,number,text,file,image',
            'options'=>($input['type'] == 'opt')?'required':''
        ]);
    

    【讨论】:

    • 这不是标准的做法。当他们为您提供方法时,您应该遵循文档。请在下面查看我的答案,也许它可以帮助你。 @tayyab_fareed
    • 是的,我检查并接受了这个答案。谢谢
    【解决方案2】:

    你可以在 Laravel 中使用 required_if 验证。

    $this->validate($request, [
        'type' => 'required|in:opt,number,text,file,image',
        'options'=> 'required_if:type,==,opt'
    ]);
    

    这是一个文档link

    【讨论】:

    • 这似乎是更好的解决方案。谢谢
    猜你喜欢
    • 2011-09-20
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多