Jump to content

Preg Match decimal point


perky416

Recommended Posts

Hi Guys,

 

I have a form field that i need verifying. Im currently using the following to check that only numbers have been entered.

 

if (preg_match('/[0-9\s]/', $price))
{
$error[] = "The price you have entered is invalid!<br />";
}

 

However id like to allow a decimal point / full stop in the text field, as well as validate that there are only 2 numbers after the decimal point if one has been entered.

 

Does anybody have any ideas how to modify the above code to allow this?

 

Many thanks.

Link to comment
https://forums.phpfreaks.com/topic/230006-preg-match-decimal-point/
Share on other sites

Before offering up a hand with the decimals, are you aware that your current regular expression only makes sure that the price has a single digit or whitespace character (space, tab, etc.) but can contain any other characters as well?  For example "this is not a number" will be accepted! Can you see why?

 

Have you had a stab at allowing decimals yourself? Either way, take a moment to browse around a reference site [1] and try to familiarize yourself with the regex approach to problem solving (not everyone gets it).  Have a stab at it yourself; folks here much prefer teaching people to fish (or, code) over giving others a free meal (though, if you're lucky!).

 

[1] E.g. http://www.regular-expressions.info

Hi Salathe,

 

Sorry I missed out the ^ in the code above, it should have read:

 

if (preg_match('/[^0-9\s]/', $price))

 

It should only accept numbers now (i have absolutely no clue why). With regards to white space, when i create the variable I use ltrim and rtrim.

 

I tried to get my head round regex a few days ago, simply to make find and replace easier for me in dreamweaver, i found it that mind boggling and confusing that in the end i gave up.

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.