我必须验证一个价格字段,该字段需要大于零(0.01 有效),因此我进行以下验证:
$request->validate([
'product_price' => 'required|numeric|gt:0',
]);
问题是,当我在“product_price”字段中输入字符串时,出现错误:
InvalidArgumentException The values under comparison must be of the same type
这是为什么呢?我的意思是,我在检查它是否 > 0 之前检查它是否应该是数字
最佳答案
Laravel 5.6 及更高版本中添加了
gt
、gte
、lt
和 lte
,我是猜测这一定是您收到错误的原因。 (不过它对我有用。)
我想你可以这样尝试
$request->validate([
'product_price' => 'required|numeric|min:0|not_in:0',
]);
min:0
确保最小值为 0 并且不允许有负值。 not_in:0
确保值不能为 0。因此,这两个规则的组合可以完成这项工作。
您可以为某些规则定义有意义的错误消息。 (您也可以使用正则表达式获得相同的结果。)
关于php - Laravel:验证大于零的数字失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397729/