使用其他字段作为 Laravel 中验证逻辑的一部分的自定义验证规则

问题描述 投票:0回答:2

我有一个自定义表单请求,有 2 个字段

amount
currency

有一些允许金额的验证规则,但它们取决于货币是什么。

所以我想创建一个自定义

ValidAmountRule
,它可以根据货币确定最大和最小金额。

如何从金额字段的验证规则访问货币属性?

laravel laravel-validation
2个回答
0
投票

你可以这样做:

'amount' => [
    'required',
    function ($attribute, $value, $fail) {
        // using global helper function
        if (request()->currency === 'foo' && request()->amount < 100) {
            $fail('The Amount has to be above 100 if currency is foo');
        }
         
        // or incase you are using a Form Request and don't like using 
        // global helper functions
        if ($this->input('currency') === 'foo' && $this->input('amount') < 100) {
            $fail('The Amount has to be above 100 if currency is foo');
        }

    },
],

来源:Laravel 自定义规则


-1
投票

对我来说最好、最快的方法是使用闭包: https://laravel.com/docs/8.x/validation#using-closures

© www.soinside.com 2019 - 2024. All rights reserved.