Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel price validation only accept positive number and not only 0

I want to validate a "price" field in Laravel.

The price should only contain numbers without (.) or (,) and cant start with 0 as well.

Eg

2500 // Pass

02500 // Fails

12.12 // Fails

12,12 / Fails

The rule I have now looks like this:

'price' => 'required|integer|not_in:0',

It seems to work with the example above, however I dont understand it. Why does not integer allow something like 0123 with a starting zero. I just want to make sure that my rule works as excpected and that I dont miss something

Thanks

like image 725
user2722667 Avatar asked Mar 10 '18 18:03

user2722667


3 Answers

This works for me:

'price' => 'required|numeric|gt:0',
like image 89
Nikolay Traykov Avatar answered Oct 17 '22 05:10

Nikolay Traykov


You can format the input before sending it to the validator in your Request class.

   public function formatInput()
{
  $input = array_map('trim', $this->all());

  $input['price'] = (int)($input['price']);
  $this->replace($input);
  return $this->all();
}

Then you can use

'price' => 'required|integer|min:0',

Hope this helps

like image 43
Romantic Dev Avatar answered Oct 17 '22 05:10

Romantic Dev


if you're not sure about the rule "integer", you can use the regex expression validation as following :

'price' => 'required|regex:^[1-9][0-9]+|not_in:0',

I had some issue same way as you, and since then i always used the regex validation for this kind of requirements. Furthermore it allow you to take back the same regex if you want to make a front validation with js.

Here is the laravel function allowing to validate integers :

public function validateInteger($attribute, $value)
{
    return filter_var($value, FILTER_VALIDATE_INT) !== false;
}

SO it's PHP itself that is concerned by this behavior. PHP tells us this thing about FILTER_VALIDATE_INT :

Validates value as integer, optionally from the specified range, and converts to int on success.

No other informations are set by PHP about the "0" value, but it's known that this function doesn't consider numbers starting by "0".

like image 7
kevinniel Avatar answered Oct 17 '22 03:10

kevinniel