【问题标题】:How to validate 2 Laravel fields in a NAND way如何以 NAND 方式验证 2 个 Laravel 字段
【发布时间】:2020-04-18 01:13:45
【问题描述】:

我正在寻找以下情况的解决方案:我的控制器操作接收 2 个变量,但它们必须相互排除。所以你可以通过其中一个或一个都不通过。

以下真值表出现(NAND):

| A | B | Result |
|---|---|--------|
| 0 | 0 |   1    |
| 0 | 1 |   1    |
| 1 | 0 |   1    |
| 1 | 1 |   0    |

(比如A 等于pointsB 等于coupon)。

// MyController.php
$this->validate($request, [
    'points' => '',
    'coupon' => ''
]);

我尝试了一些解决方案,例如 nullable|required_without:field_name,但这些解决方案似乎会导致 XOR,这意味着您必须至少通过其中的 1 个。

【问题讨论】:

    标签: laravel validation laravel-5


    【解决方案1】:

    我决定创建一个名为 without:field1,field2 的新规则:

    Validator::extend('without', function($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
        foreach($parameters as $compare) {
            // Check if the given parameters are filled in, if so we return `false`.
            if($validator->validateRequired(null, array_get($validator->getData(), $compare))) {
                return false;
            }
        }
        // No `without` parameters have been found, validation successful.
        return true;
    });
    
    // Replace the error message placeholders.
    Validator::replacer('without', function ($message, $attribute, $rule, $parameters, \Illuminate\Validation\Validator $validator) {
        $attributes = [];
        foreach ($parameters as $key => $value) {
            $attributes[$key] = $validator->getDisplayableAttribute($value);
        }
        return str_replace(':values', implode(' / ', $attributes), $message);
    });
    

    接下来,给resources/lang/en/validation.php添加翻译:

        'without'              => 'The :attribute may not be set with :values',
    

    那么你可以像这样简单地使用它:

    $this->validate($request, [
        'points' => 'nullable|without:coupon',
        'coupon' => 'nullable|without:points'
    ]);
    

    (您可以添加多个参数,如without:coupon,user_id

    确保:

    • 同时传递 pointscoupon 会导致验证错误
    • 通过其中一个就可以了
    • 两者都不能通过

    【讨论】:

    • 您还可以通过返回对 if 条件的否定来缩短验证闭包。
    • @mdexp 看起来不像,因为我在循环中使用它
    • 你说得对,我在移动设备上错过了 foreach。
    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2015-12-25
    • 2023-03-27
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多