woolyg Posted October 1, 2008 Share Posted October 1, 2008 Hi all, I'm trying to validate a number entry - say a user enters 100 - allow it, 100.23 - allow it 100.234 - disallow it 100text - disallow it Can anyone help me with the preg_match validator? I've tried looking it up, but I'm getting errors regarding delimiters. Thanks, WoolyG Quote Link to comment Share on other sites More sharing options...
corbin Posted October 1, 2008 Share Posted October 1, 2008 /^([0-9.]+)$/ Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted October 1, 2008 Share Posted October 1, 2008 /^([0-9.]+)$/ Corbin, the problem with this pattern is that it will even satisfy 100.234 Here is my take: $str = '1004325.23'; if (preg_match('#^\d+(?:\.\d{1,2})?$#', $str, $match)){ echo $match[0] . ' is valid!'; } else { echo $str . ' is NOT valid!'; } This pattern assumes: a) no limit to the amount of numbers prior to a decimal point (if there even is a decimal with digits after it) b) if there is a decimal, there is a minimum of 1 digit, and a maximum of 2 digits).. [if the OP only wants 2 digits after the decimal, change \d{1,2} to \d{2}] Cheers, NRG Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted October 1, 2008 Share Posted October 1, 2008 or... function is_valid($number){ if(is_numeric){ list($nu,$de) = explode('.',$number); return (strlen($de) < 3 || !isset($de)) ? TRUE : FALSE; }else{ return FALSE; } } Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted October 1, 2008 Share Posted October 1, 2008 or... function is_valid($number){ if(is_numeric){ list($nu,$de) = explode('.',$number); return (strlen($de) < 3 || !isset($de)) ? TRUE : FALSE; }else{ return FALSE; } } this line: if(is_numeric){ should be: if(is_numeric($number)){ as is_numeric is a function call that requires a single argument. With your current code, an assumed constant 'is_numeric' error occurs. Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted October 1, 2008 Share Posted October 1, 2008 Oops, sorry, forgot that Good catch! Quote Link to comment Share on other sites More sharing options...
corbin Posted October 2, 2008 Share Posted October 2, 2008 Oh hehe didn't realize he only wanted 2 decimals. 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.