1

I'm using laravel validation system. And I have a field is database as wholesale_price and price is decimal. For validation I'm using this.

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

But price cannot be 0. And I have to validate > 0

How can I do that. In laravel min:1 functionality but this is not useful for me. Because I have prices like 0.005 or 0.02

1

2 Answers 2

4

You shouldn't have to do regex to solve this. Take the following test for example:

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

As long as your require the numeric rule, then between will treat the value being validated as a number (int, float, double, etc.) As long as your don't pass a string value such as $0.001, or strip any unwanted characters prior to validation, this method will return true for anything above 0 and the max value you set (currently 99.99, but you can set it as high as you'd like.)

Here's a simple testing template:

$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;

Note: Also works if price is a string value, just strip the $ if you're sending that to the server.

Hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :P Stumbled across the reason why that numeric rule is required; if you don't have it, between treats the value as a string, and checks its strlen() value against the rule, so strlen("0.001") is 5, and falls between 0.001 and 99.99, thus always passing the validation.
0

How about this regex:

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

Explanation:

^            # 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

Conclusion:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.