Rafael Sedrakyan
Rafael Sedrakyan

Reputation: 2629

PHP regex for validating currency

I need a regex to validate currency. Allowed values are:

1209
1889.0
578247.00
75646.50
But not 44565.12

The second number after comma must be 0. And available currency range is 0.1-9999999.9 . Thanks for help.

Upvotes: 1

Views: 888

Answers (2)

James C
James C

Reputation: 14149

As others have suggested a regex isn't the best way of dealing with numbers.

You could add additional simple range checks to the code below if needed and it'll be considerably faster than trying to do this with regexps

<?php

$a = array(
1209,
1889.0,
578247.00,
75646.50,
44565.12
);

foreach ($a as $b) {
    echo "$b - ";
    echo ($b*100 % 50) == 0 ? 'PASS' : 'FAIL';
    echo PHP_EOL;
}

Upvotes: 0

shift66
shift66

Reputation: 11958

use this pattern: ([1-9]\d{,6}|0)(\.\d0?)?
with this pattern 1234.2 will be allowed.is it OK? I edited the pattern, take a look.
First digit can't be 0 if there are other digits before the dot. So number must start with a non-zero digit and can have at most 6 digits after first and before dot or can have only zero before dot ( this part([1-9]\d{,6}|0)). \d0? means one digit and there may be a zero after it. \. is just a dot.

Upvotes: 1

Related Questions