简体   繁体   English

Laravel 验证:required_if 条件始终通过

[英]Laravel Validation: required_if condition always passing

As per laravel validation documentation:根据 laravel 验证文档:

required_if:anotherfield,value,... The field under validation must be present and not empty if the anotherfield field is equal to any value. required_if:anotherfield,value,... 如果 anotherfield 字段等于任何值,则验证字段必须存在且不为空。

Here is my test:这是我的测试:

    $validator = Validator::make([
        'assessment' => [
            'hasConfirmation' => 0,
            'expiredDate' => "12/2020"
        ]
    ],
        [
            'assessment.hasConfirmation' => Rule::in([0, 1, null]),
            'assessment.expiredDate' => Rule::requiredIf('assessment.hasConfirmation' === 1),

        ]);

   $validator->passes(); // always return true

I would expect that since I am not passing 1, this test should fail.我希望因为我没有通过 1,所以这个测试应该失败。 But this test always passes但是这个测试总是通过

You can use a closure with requiredIf that returns a boolean to determine if the 'required' rule should be applied:您可以使用requiredIf的闭包返回 boolean 来确定是否应应用“必需”规则:

$data = [
    'assessment' => [
        'hasConfirmation' => 0,
        'expiredDate' => "12/2020"
    ]
];

$validator = Validator::make($data, [
    'assessment.hasConfirmation' => Rule::in([0, 1, null]),
    'assessment.expiredDate' => Rule::requiredIf(function () use ($data) {
        return data_get($data, 'assessment.hasConfirmation') === 1;
    });
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM