Jump to content

!preg_match line for decimal number


JayDude

Recommended Posts

I want to validate a form field for a number with two decimals (ie. 894567.29),

but my script gives me an error, asking me to correct the entry,

Following is a snippet of the script:-

 

elseif($field == "oil_waste_ltr")

{

if(!preg_match("/^[0-9]{1,10}\.{2}$/",$value) )

{

$bad_format[] = $field;

}

}

Link to comment
https://forums.phpfreaks.com/topic/259964-preg_match-line-for-decimal-number/
Share on other sites

All my script is now working fine, but how do I fix the fact that some values will have

a zero decimal and the user do not enter a decimal

(ie 5269, the database should then enter the data as 5269.00) this minor issue asks me to correct the input.

In other words, the user should not be forced to enter a value with a digit...

 

if(!preg_match("~^[0-9]{1,10}\.[0-9]{1}$~",$value) )

 

You can make the entire decimal part optional

 

$regExp = '~^[0-9]{1,10}(\.[0-9]{0,2})?$~';

$values = array('123.45', '123', '123.', '123.5', 'abc', '123a21');

foreach ($values as $ind => $value) {
$match = preg_match($regExp, $value);
printf("%d: %s -- %d\n", $ind, $value, $match);
}

 

output

0: 123.45 -- 1
1: 123 -- 1
2: 123. -- 1
3: 123.5 -- 1
4: abc -- 0
5: 123a21 -- 0

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.