You need to enable JavaScript to run this app. Laravel中如何验证5个输入字段的总金额在1-10000之间?
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何验证5个输入字段的总金额在1-10000之间?

解决Laravel中现金交易总金额范围验证问题

原代码存在的核心问题

  1. 金额计算错误:amount()方法仅累加各字段的数量值,未乘以对应纸币的面额,导致总金额计算完全错误。
  2. 无效验证规则:使用了请求中不存在的total_amount字段,这部分验证规则不会生效。

修正后的完整代码

<?php

namespace App\Services;

use App\Services\Interfaces\TransactionInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CashTransaction implements TransactionInterface
{
    protected array $inputs = [];

    public function __construct(array $inputs)
    {
        unset($inputs['_token']);
        
        // 为每个面额字段设置默认值0,避免计算时出现未定义索引
        $defaultFields = [
            'one_dollar' => 0,
            'five_dollars' => 0,
            'ten_dollars' => 0,
            'fifty_dollars' => 0,
            'hundred_dollars' => 0,
        ];
        
        $this->inputs = array_merge($defaultFields, $inputs);
    }

    public function validate(Request $request): array
    {
        $validator = Validator::make($request->all(), [
            'one_dollar' => 'nullable|integer|min:0',
            'five_dollars' => 'nullable|integer|min:0',
            'ten_dollars' => 'nullable|integer|min:0',
            'fifty_dollars' => 'nullable|integer|min:0',
            'hundred_dollars' => 'nullable|integer|min:0',
        ]);

        // 添加自定义总金额范围验证
        $validator->after(function ($validator) {
            $totalAmount = $this->amount();
            
            if ($totalAmount < 1) {
                $validator->errors()->add('total_amount', '总金额不能低于1');
            } elseif ($totalAmount > 10000) {
                $validator->errors()->add('total_amount', '总金额不能超过10000');
            }
        });

        return $validator->errors()->all();
    }

    public function amount(): float
    {
        // 定义各字段对应的面额值
        $denominations = [
            'one_dollar' => 1,
            'five_dollars' => 5,
            'ten_dollars' => 10,
            'fifty_dollars' => 50,
            'hundred_dollars' => 100,
        ];

        $total = 0;

        foreach ($denominations as $field => $value) {
            // 计算单一面额的总金额并累加
            $total += $this->inputs[$field] * $value;
        }

        return round($total, 2);
    }

    public function inputs(): array
    {
        return $this->inputs;
    }
}

关键改动说明

  1. 构造函数优化:通过array_merge为所有面额字段设置默认值0,避免后续计算时出现未定义索引的问题。
  2. 修复金额计算:新增面额映射数组,循环计算每个字段的数量乘以对应面额,得到正确的总金额。
  3. 自定义验证逻辑:使用Laravel验证器的after()方法,在完成基础字段验证后,计算总金额并检查是否在1-10000范围内,不符合则添加对应错误信息。

内容的提问来源于stack exchange,提问作者Toma Tomov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:08:14