I'm trying to do a regular expression that'll allow numbers from 0.01 to 99.99, but not 0.0 or any null value (00.00 or 00.0 or 0.00 or 0.0) or negative value either. I've come quite close, but as usual something just isn't right. 0.0 shows as valid. Can you please help me fix this. Also, you don't need to keep the expression I've done :)
<?php
if (preg_match('/^[0-9]{1,2}[\.][0-9]{1,2}$/','0.0'))
{echo "Valid";}else{echo "Invalid";}
?>
Here's my attempt:
/^(?=.*[1-9])\d{0,2}(?:\.\d{0,2})?$/
First off, use a positive look-ahead ((?=.*[1-9])
) to ensure that there is at least one "significant digit" in the whole mess, will fail for all forms of 0.0
, 00.00
or whatever. The next part \d{0,2}
allows 0, 1, or 2 digits before the decimal point, then an optional group (?:)?
that includes a literal decimal, followed by 0, 1 or 2 digits: \.\d{0,2}
. Use the ^
and $
to make this expression complete by only matching from beginning to end of string.
Some quick test strings:
0.0 failed. 0 failed. 12 matched. 123 failed. 05.00 matched. 0.01 matched.
Why not
<?php
$value = '0.0';
if ($value > 0 && preg_match('/^[0-9]{1,2}[\.][0-9]{1,2}$/', $value)) {
echo "Valid";
} else {
echo "Invalid";
}
Sometimes a regex is not a solution, but rather a problem ;-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With