Jump to content

Preg_match for decimals?


woolyg

Recommended Posts

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

Link to comment
Share on other sites

/^([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

Link to comment
Share on other sites

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.

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.