具有其他条件的验证规则required_if(Laravel 5.4) [英] Validation rules required_if with other condition (Laravel 5.4)

查看:738
本文介绍了具有其他条件的验证规则required_if(Laravel 5.4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对带有嵌套条件的验证规则有疑问.

I got a problem with validation rules with nested conditions.

class StoreRequest extends Request
{
        public function authorize(){
        return true;
        }

        public function rules(){
                return [
                    'type_id'     => 'required|integer',
                    'external_id' => 'required_if:type_id,==,3|integer',
                ];
        }
}

实际上我想: -仅在type_id等于3时检查external_id -并检查它是否为整数.

Indeed I want to : - check the external_id only if the type_id equal to 3 - and check if it's an integer.

发布表单时,当我选择等于3的type_id时,规则将起作用. 但是,如果我选择另一个type_id,例如1或2,则验证不会通过:

When I post my form, the rules works when I select a type_id equal to 3. But if I select another type_id, like 1 or 2, the validation does not pass :

external_id必须为整数.

The external_id must be an integer.

我尝试添加可为空的条件,但required_if不再起作用

I try to add the nullable condition but required_if does not work anymore

你有什么主意吗?

推荐答案

您的规则执行两项彼此独立的检查;仅仅是因为type_id!= 3时不需要external_id字段,并不意味着整数检查将被忽略.

Your rule performs two checks that are independent of one another; just because the external_id field is not required when the type_id != 3, does not mean the integer check is ignored.

您要查找的是条件规则,该规则您可以更好地控制何时执行检查,例如:

What you are looking for is a conditional rule, which gives you finer control of when to perform a check, e.g. :

$validator = Validator::make($data, [
    'type_id'   => 'required|integer'
]);

$validator->sometimes('external_id', 'required|integer', function($input) {
    return $input->type_id == 3;
});

使用表单验证时,您可以通过覆盖getValidatorInstance()方法来访问基础验证器实例:

When using form validation, you can access the underlying validator instance by overriding the getValidatorInstance() method:

class StoreRequest extends Request
{
        public function authorize(){
        return true;
        }

        public function rules(){
                return [
                    'type_id'     => 'required|integer'
                ];
        }

        protected function getValidatorInstance() {
            $validator = parent::getValidatorInstance();
            $validator->sometimes('external_id', 'required|integer', function($input) {
                return $input->type_id == 3;
            });
            return $validator;
        }
}

这篇关于具有其他条件的验证规则required_if(Laravel 5.4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆