Laravel validation OR

拜拜、爱过 提交于 2019-12-21 05:16:21

问题


I have some validation that requires a url or a route to be there but not both.

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

I have tried using required_without and required_without_all however they both get past the validation and I am not sure why.

route is a rule in the route field


回答1:


I think the easiest way would be creation your own validation rule. It could looks like.

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;
});

And use it

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

P.S. Don't forget to register this in your provider.

Edit

Add custom message

1) Add message 2) Add replacer

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);
});



回答2:


I think you are looking for required_if:

The field under validation must be present if the anotherfield field is equal to any value.

So, the validation rule would be:

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


来源:https://stackoverflow.com/questions/34915547/laravel-validation-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!