【问题标题】:Laravel Not Zero ValidationLaravel 非零验证
【发布时间】:2016-03-31 02:00:20
【问题描述】:

我正在使用 laravel 验证系统。我有一个字段是数据库作为批发价格,价格是十进制的。为了验证,我正在使用它。

'wholesale_price' => 'required|regex:/^\d*(\.\d{1,2})?$/',

但价格不能为 0。而且我必须验证 > 0

我该怎么做。在 laravel min:1 功能中,但这对我没有用。因为我的价格是 0.005 或 0.02

【问题讨论】:

标签: php validation laravel


【解决方案1】:

您不必通过regex 来解决此问题。以下面的测试为例:

$input = ["wholesale_price" => 0.005];
$rules = ["wholesale_price" => "numeric|between:0.001,99.99"];

只要您需要numeric 规则,那么between 会将正在验证的值视为数字(intfloatdouble 等)只要您不需要传递一个字符串值,例如$0.001,或在验证之前去除任何不需要的字符,此方法将为高于0 和您设置的最大值(当前为99.99,但您可以将其设置为最高)返回true你喜欢。)

这是一个简单的测试模板:

$input = [
    "price" => 0
];
$input2 = [
    "price" => 0.001
];
$rules = [
    "price" => "numeric|between:0.001,99.99",
];

$validator = \Validator::make($input, $rules);
$validator2 = \Validator::make($input2, $rules);

dd($validator->passes());
// Returns false;

dd($validator2->passes());
// Returns true;

注意:如果price 是一个字符串值,也可以使用,如果您将其发送到服务器,只需去掉$

希望有帮助!

【讨论】:

  • 谢谢 :P 偶然发现了需要 numeric 规则的原因;如果没有,between 将值视为string,并根据规则检查其strlen() 值,因此strlen("0.001")5,介于0.001 and 99.99 之间,因此总是通过验证。
【解决方案2】:

这个正则表达式怎么样:

/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/

解释:

^            # Start of string
\s*          # Optional whitespace
(?=.*[1-9])  # Assert that at least one digit > 0 is present in the string
\d*          # integer part (optional)
(?:          # decimal part:
 \.          # dot
 \d{1,2}     # plus one or two decimal digits
)?           # (optional)
\s*          # Optional whitespace
$            # End of string

结论:

'wholesale_price' => 'required|regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 2015-03-21
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多