Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match validate price format

Tags:

php

I'd like to validate a numeric field (price) in my form.
I try in this way to validate format like 10.00 and it's ok.

$pattern = '/^\d+(:?[.]\d{2})$/';

if (preg_match($pattern, $_POST['price']) == '0') {
   echo "ERROR";
   exit;
}

Now I'd like to validate, at the same time, the field format like 10.00 and 10. How could I do this?

like image 811
Paolo Rossi Avatar asked Oct 08 '13 15:10

Paolo Rossi


1 Answers

Your new pattern:

$pattern = '/^\d+(\.\d{2})?$/';

will validate:

10
10.00

If you want to invalidate zero-leading numerics such as 05.00, the following pattern will help:

$pattern = '/^(0|[1-9]\d*)(\.\d{2})?$/';
like image 178
Kita Avatar answered Sep 28 '22 05:09

Kita