根据另一个字段的值来验证Laravel字段

6

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

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

10

在Laravel中,您可以使用required_if验证。

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

Here is a Documentation link


这似乎是更好的解决方案。谢谢。 - tayyab_fareed

1
你可以这样有条件地添加验证:

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

这不是标准的做法。当文档提供了一种方式时,您应该遵循它。请检查下面我的答案,也许可以帮到你。@tayyab_fareed - SRK
是的,我已经检查并接受了那个答案。谢谢。 - tayyab_fareed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接