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
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) )

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.