如何验证Laravel中值的总和



我在blade.php中有3个类型为number的输入标记。我想验证总和是否等于100。那么,如何做到这一点呢?谢谢你的帮助。

Blade.php

<input type="number" name="number1" />
<input type="number" name="number2" />
<input type="number" name="number3" />

控制器

public function store(Request $request) {
$data = $request->validate([
'number1' => 'required',
'number2' => 'required',
'number3' => 'required',
]);
$sum = $data['number1'] + $data['number2'] + $data['number3'];
$myDb = new Mynumber();
$myDb->number1 = $data['number1'];
$myDb->number2 = $data['number2'];
$myDb->number3 = $data['number3'];
$myDb->save();
}

您可以通过在服务提供商中添加新规则来扩展验证器:

$validator->extend("sumsTo", function ($attribute, $value, $parameters) {
$expected = floatval(array_shift($parameters));
$otherParameters = request()->only($parameters);
return floatval(array_sum(array_merge(array_values($otherParameters), [ $value ]))) === $expected;
});

然后你会用这个作为:

$request->validate([
'field1' => 'sumsTo:100,field2,field3',
'field2' => 'sumsTo:100,field1,field3'
'field3' => 'sumsTo:100,field1,field2'
]);

这也会将所有3个字段标记为失败。

如果你想保持在Laravels验证器的边界内,我建议你要么使用验证后挂钩,要么创建一个临时字段(在PHP中,不要使用客户端技术!(,其中包含所有必要字段的总和,并根据它进行验证。

$validator = Validator::make([
'field1' => 50,
'field2' => 25,
'field3' => 22,
], [
'field1' => 'required|numeric',
'field2' => 'required|numeric',
'field3' => 'required|numeric',
]);
$validator->after(function ($validator) {
if ($validator->getData()['field1'] + $validator->getData()['field2'] + $validator->getData()['field3'] !== 100) {
$validator->errors()->add('field1', 'Make sure the sum of all fields equals 100.');
}
});

相关内容

  • 没有找到相关文章

最新更新