perky416 Posted March 8, 2011 Share Posted March 8, 2011 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. Quote Link to comment Share on other sites More sharing options...
salathe Posted March 8, 2011 Share Posted March 8, 2011 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 Quote Link to comment Share on other sites More sharing options...
perky416 Posted March 8, 2011 Author Share Posted March 8, 2011 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. Quote Link to comment Share on other sites More sharing options...
perky416 Posted March 8, 2011 Author Share Posted March 8, 2011 Iv managed to get it to accept the decimal place by adding \. to make the code: if (preg_match('/[^0-9\.\s]/', $price)) I still cant figure out how to make it accept up to 2 decimal places. Quote Link to comment Share on other sites More sharing options...
sasa Posted March 8, 2011 Share Posted March 8, 2011 try <?php $price = ' 123.3'; if(preg_match('/^\s*\d*\.?\d{1,2}\s*$/', $price)) echo "ok"; else echo "no"; ?> Quote Link to comment Share on other sites More sharing options...
perky416 Posted March 8, 2011 Author Share Posted March 8, 2011 try <?php $price = ' 123.3'; if(preg_match('/^\s*\d*\.?\d{1,2}\s*$/', $price)) echo "ok"; else echo "no"; ?> Thanks mate it works perfectly, Thanks!!! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.