Laravel:验证大于零的数字失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52397729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:04:10  来源:igfitidea点击:

Laravel: Validating a number greater than zero is failing

phplaravelvalidationlaravel-validation

提问by MrCujo

I gotta validate a price field which needs to be greater than zero (0.01 is valid) so I have the following validation:

我必须验证一个需要大于零的价格字段(0.01 是有效的),所以我有以下验证:

$request->validate([
            'product_price' => 'required|numeric|gt:0',
        ]);

The problem is that when I enter a string in the 'product_price' field I'm getting an error:

问题是,当我在“product_price”字段中输入字符串时,出现错误:

InvalidArgumentException The values under comparison must be of the same type

InvalidArgumentException 比较的值必须是同一类型

why is that? I mean, I'm checking that it should be numeric before even checking that it's > 0

这是为什么?我的意思是,在检查它是否 > 0 之前,我正在检查它是否应该是数字

回答by TharinduLucky

gt, gte, ltand lteare added in Laravel 5.6 and later versions, I'm guessing that must be the reason for you get the error. (It's working for me though.)

gt, gte,ltlteLaravel 5.6 及更高版本中添加,我猜这一定是您收到错误的原因。(不过它对我有用。)

I think you can try like this

我想你可以这样试试

$request->validate([
    'product_price' => 'required|numeric|min:0|not_in:0',
]);

min:0make sure the minimum value is 0 and no negative values are allowed. not_in:0make sure value cannot be 0. So, combination of both of these rules does the job.

min:0确保最小值为 0 并且不允许使用负值。not_in:0确保值不能为 0。因此,这两个规则的组合可以完成这项工作。

You can define meaningful error messages for certain rule. (You can achieve the same result using regular expressions as well.)

您可以为特定规则定义有意义的错误消息。(您也可以使用正则表达式获得相同的结果。)

回答by Mayank Majithya

You can try this way ,

你可以试试这个方法

Before invoking the Validator::make() function, modify the set of rules by appending the value to compare to like so:

在调用 Validator::make() 函数之前,通过附加要比较的值来修改规则集,如下所示:

use Illuminate\Support\Facades\Validator;

Validator::extend('greater_than', function ($attribute, $value, $otherValue) {
      return intval($value) > intval($otherValue[0]);
});

$validation = Validator::make($input, ['amount' => 'required|numeric|greater_than:0']);

回答by Chandan Sharma

For me, this code is working in my project.

对我来说,这段代码在我的项目中有效。

$validation_rules = array( 
                'user_id' => 'required|integer|gt:0',
                'type_id' => 'required|integer|gt:0',
            );
$validation = Validator::make($request->all(), $validation_rules);

Here, gt:0 check if the integer is greater than zero.

在这里, gt:0 检查整数是否大于零。

Hope, this will work for you. If not then please check your Laravel version.

希望,这对你有用。如果没有,请检查您的 Laravel 版本。

回答by effy

I can see that none of the other answers have really addressed the real reason you're getting this error, I'll try and provide some insights and a solution to it.

我可以看到其他答案都没有真正解决您收到此错误的真正原因,我将尝试提供一些见解和解决方案。

The problem here is that Laravel is testing all validation rules and not stopping after the first validation error which in your case is numeric(which fails since the value provided is a string), if it did that the error with the gtvalidator being provided a string value wouldn't be thrown since the validator has already exited after the numericerror.

这里的问题是 Laravel 正在测试所有验证规则,并且不会在第一个验证错误之后停止,在您的情况下numeric(由于提供的值是字符串而失败),如果确实如此,则gt验证器的错误被提供了一个字符串值不会被抛出,因为验证器在numeric错误后已经退出。

To have Laravel stop the validation checks after the first failed validation rule, you can prefix your validation rules with the bailvalidator which basically tells Laravel to stop after the first error.

要让 Laravel 在第一个失败的验证规则后停止验证检查,您可以在验证规则前加上bail验证器,这基本上告诉 Laravel 在第一个错误后停止。

The resulting code would look like this:

生成的代码如下所示:

$request->validate([
    'product_price' => 'bail|required|numeric|gt:0',
]);

Note that this solution also makes it so that only a single error is ever returned per field, if in your UI you usually display all the errors for a particular field at a time (instead of only picking the first one from the message bag), this solution would change that.

请注意,此解决方案还使每个字段只返回一个错误,如果在您的 UI 中您通常一次显示特定字段的所有错误(而不是仅从消息包中选择第一个),这个解决方案将改变这一点。

More information on the bailvalidation rule can be found here: https://laravel.com/docs/6.x/validation#rule-bail

有关bail验证规则的更多信息,请访问:https: //laravel.com/docs/6.x/validation#rule-bail