我有一个自定义表单请求,有 2 个字段
amount
和 currency
。
有一些允许金额的验证规则,但它们取决于货币是什么。
所以我想创建一个自定义
ValidAmountRule
,它可以根据货币确定最大和最小金额。
如何从金额字段的验证规则访问货币属性?
你可以这样做:
'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');
}
},
],
对我来说最好、最快的方法是使用闭包: https://laravel.com/docs/8.x/validation#using-closures