本文介绍了仅当另一个字段具有值时,才为必填字段,否则必须为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于Laravel 验证规则.

My question is about Laravel validation rules.

我有两个输入ab. a是具有三个可能值的选择输入:xyz.我要编写此规则:

I have two inputs a and b. a is a select input with three possible values: x, y and z. I want to write this rule:

有没有办法写这样的规则?我尝试了required_withrequired_without,但似乎无法解决我的情况.

Is there a way to write such a rule? I tried required_with, required_without but it seems it can not cover my case.

换句话说,如果前面的解释不够清楚:

In other words, if the previous explanation was not clear enough:

  • 如果a == x,则b必须具有一个值.
  • 如果a!= x,则b必须为空.
  • If a == x, b must have a value.
  • If a != x, b must be empty.

推荐答案

您必须创建自己的验证规则.

You have to create your own validation rule.

编辑app/Providers/AppServiceProvider.php并将此验证规则添加到boot方法:

Edit app/Providers/AppServiceProvider.php and add this validation rule to the boot method:

// Extends the validator
\Validator::extendImplicit(
    'empty_if',
    function ($attribute, $value, $parameters, $validator) {
        $data = request()->input($parameters[0]);
        $parameters_values = array_slice($parameters, 1);
        foreach ($parameters_values as $parameter_value) {
            if ($data == $parameter_value && !empty($value)) {
                return false;
            }
        }
        return true;
    });

// (optional) Display error replacement
\Validator::replacer(
    'empty_if',
    function ($message, $attribute, $rule, $parameters) {
        return str_replace(
            [':other', ':value'], 
            [$parameters[0], request()->input($parameters[0])], 
            $message
        );
    });

(可选)resources/lang/en/validation.php中的错误创建消息:

(optional) Create a message for error in resources/lang/en/validation.php:

'empty_if' => 'The :attribute field must be empty when :other is :value.',

然后在控制器中使用此规则(通过require_if遵守原始帖子的两个规则):

Then use this rule in a controller (with require_if to respect both rules of the original post):

$attributes = request()->validate([
    'a' => 'required',
    'b' => 'required_if:a,x|empty_if:a,y,z'
]);

有效!

侧面说明:我可能会使用empty_ifempty_unless创建一个满足此需求的程序包,并将链接发布在此处

Side note: I will maybe create a package for this need with empty_if and empty_unless and post the link here

这篇关于仅当另一个字段具有值时,才为必填字段,否则必须为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:35