Laravel验证 OR

7

我有一些验证需要一个 URL 或路径存在,但不能同时存在。

    $this->validate($request, [
        'name'  =>  'required|max:255',
        'url'   =>  'required_without_all:route|url',
        'route' =>  'required_without_all:url|route',
        'parent_items'=>  'sometimes|required|integer'
    ]);

我尝试使用required_withoutrequired_without_all,但它们都可以通过验证,我不确定原因。

routeroute字段中的规则。


我刚刚尝试使用了 required_without,它可以正常工作。你能发布一下你的 route 规则吗?我的规则是 return ['route' => "required_without:url", 'url' => "required_without:route|url"];,对我来说效果很好。 - Ben Swinburne
@BenSwinburne 请看下面的答案和我的评论,需要的完全是错误的事情 :) - Ian
2个回答

13

我认为你正在寻找required_if

如果anotherfield字段等于任何值,则验证的字段必须存在。

因此,验证规则应该是:

$this->validate($request, [
    'name'        =>  'required|max:255',
    'url'         =>  'required_if:route,""',
    'route'       =>  'required_if:url,""',
    'parent_items'=>  'sometimes|required|integer'
]);

1
很遗憾,这并没有帮助,当两个字段都被填充时,验证仍然通过。 - Ian
@Ian 只是一个想法:为什么不使用jQuery?例如,如果用户正在填写“url”字段,则将“只读”属性添加到“route”字段,反之亦然。这样,如果其中一个字段已经填写了数据,他们将无法填写数据。 - Saiyan Prince
12
他们可以删除那个属性,然后仍然通过服务器端处理,jQuery不是解决服务器端问题的方案。 - Ian

5
我认为最简单的方法是创建自己的验证规则。它可能看起来像这样:

我认为最简单的方法是创建自己的验证规则。它可能看起来像这样。

Validator::extend('empty_if', function($attribute, $value, $parameters, Illuminate\Validation\Validator $validator) {

    $fields = $validator->getData(); //data passed to your validator

    foreach($parameters as $param) {
        $excludeValue = array_get($fields, $param, false);

        if($excludeValue) { //if exclude value is present validation not passed
            return false;
        }
    }

    return true;
});

并使用它

    $this->validate($request, [
    'name'  =>  'required|max:255',
    'url'   =>  'empty_if:route|url',
    'route' =>  'empty_if:url|route',
    'parent_items'=>  'sometimes|required|integer'
]);

P.S. 别忘了在你的服务商注册这个。

编辑

添加自定义消息

1)添加消息 2)添加替换器

Validator::replacer('empty_if', function($message, $attribute, $rule, $parameters){
    $replace = [$attribute, $parameters[0]];
    //message is: The field :attribute cannot be filled if :other is also filled
    return  str_replace([':attribute', ':other'], $replace, $message);
});

太好了!今天早上我意识到 required_if 并不是我需要的,实际上是用来检查另一个字段是否为空,感谢你的帮助。 - Ian
关于消息规则存在一些小问题,由于它是自定义验证规则,所以在消息中不会进行相同的替换。如果我只设置为静态消息,则由于两个字段使用相同的角色,它将出现两次。您能否扩展您的答案以包括消息?例如 如果同时填写 :other,则无法填写字段 :attribute?我找到的最接近的方法在 \vendor\laravel\framework\src\Illuminate\Validation\Validator.php 的第1680行。 - Ian
1
又一次完美!我以为可能与 $this->validate() 的第三个参数有关,但是不是,谢谢! :) - Ian

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