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

Link to comment
Share on other sites

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.

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.