我有一个自定义表单请求,有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');
}
},
],
来源:Laravel Custom Rules
试试这个
$request->validate([
'currency' => 'required',
'amount' => 'required_if:currency, USD|numeric|between:1,100',
'amount' => 'required_if:currency, EUR|numeric|between:1,50',
]);参考
https://laravel.com/docs/10.x/validation rule-required-if
对我来说最好和最快的方法是使用闭包:https://laravel.com/docs/8.x/validation使用闭包