Laravel自定义验证规则开发:实现net_weight=loaded_weight-empty_weight
Laravel自定义验证规则实现重量公式校验
要确保表单中net_weight等于loaded_weight减去empty_weight,可以通过以下步骤实现自定义验证规则:
1. 创建自定义验证规则类
在终端执行Artisan命令生成规则文件:
php artisan make:rule WeightFormulaMatch
2. 编写规则校验逻辑
打开生成的app/Rules/WeightFormulaMatch.php文件,替换内容如下:
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class WeightFormulaMatch implements Rule { /** * 验证规则是否通过 * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { $emptyWeight = request()->input('empty_weight'); $loadedWeight = request()->input('loaded_weight'); // 校验字段是否为有效数值 if (!is_numeric($emptyWeight) || !is_numeric($loadedWeight) || !is_numeric($value)) { return false; } // 转换为浮点类型确保计算精度 $emptyWeight = (float)$emptyWeight; $loadedWeight = (float)$loadedWeight; $netWeight = (float)$value; // 验证公式逻辑,同时避免总重小于空车重量导致净重为负 return $loadedWeight >= $emptyWeight && ($loadedWeight - $emptyWeight) === $netWeight; } /** * 获取验证失败的错误消息 * * @return string */ public function message() { return '净重必须等于总重减去空车重量,且总重不能小于空车重量'; } }
3. 在验证流程中使用规则
方式一:表单请求类中使用
如果使用表单请求(如StoreWeightRequest.php),在rules方法中添加规则:
public function rules() { return [ 'empty_weight' => 'required|numeric|min:15000|max:35000|step:20', 'loaded_weight' => 'required|numeric|min:35000|max:120000|step:20', 'net_weight' => ['required', 'numeric', 'step:20', new WeightFormulaMatch], ]; }
方式二:控制器直接验证
在控制器方法中调用validate方法时引入规则:
use App\Rules\WeightFormulaMatch; public function store(Request $request) { $validated = $request->validate([ 'empty_weight' => 'required|numeric|min:15000|max:35000|step:20', 'loaded_weight' => 'required|numeric|min:35000|max:120000|step:20', 'net_weight' => ['required', 'numeric', 'step:20', new WeightFormulaMatch], ]); // 后续业务逻辑处理 }
额外说明
- 规则中增加了
loaded_weight >= empty_weight的校验,避免出现净重为负的不合理数据 - 所有字段均做数值类型校验,确保计算逻辑的准确性
- 错误提示可根据业务需求在
message()方法中修改
内容的提问来源于stack exchange,提问作者Echo Mind
相关产品推荐
相关产品推荐

