Jump to content

How to check if a variable has a number on it?


bugzy

Recommended Posts

Probably overkill but yeah...

 

function containsInteger($input) {
return (boolean)preg_match("/[0-9]/", $input);
}

 

 

Hello,

 

I tried this

 

 

preg_match("/[0-9]/", $address) == FALSE

 

and this

 

!preg_match("/[0-9]/", $address)

 

 

But it's not working like...

 

like if I input "Hello World"

 

It's returning a true value even if there's no number included on the input

 

:shrug:

 

 

if(strlen($address) < 20 && !empty($address) && !preg_match("/[0-9]/", $address))
   {
      //invalid
   }

 

As Pikachu stated that could be written more logically and it actually has a flaw. If the user entered the number '0' the validation would fail because the function empty() would return false. But, let's step back a second because that is really overkill. If you must have a check to ensure there is at least 1 number in the value there is no need to do the strlen() or empty() checks at all!

 

Also, I normally do an isset() check on form field values. It could be considered overkill, but I incorporate it with a process to also trim the values which you should be doing anyway. So, here's my take:

 

$address = isset($_POST['address']) ? trim($_POST['address']) : '';
if(!preg_match("/[0-9]/", $address ))
{
    //Invalid
    echo "The value '$address' is invalid"; //Add this for debugging
}

 

if(strlen($address) < 20 && !empty($address) && !preg_match("/[0-9]/", $address))
   {
      //invalid
   }

 

As Pikachu stated that could be written more logically and it actually has a flaw. If the user entered the number '0' the validation would fail because the function empty() would return false. But, let's step back a second because that is really overkill. If you must have a check to ensure there is at least 1 number in the value there is no need to do the strlen() or empty() checks at all!

 

Also, I normally do an isset() check on form field values. It could be considered overkill, but I incorporate it with a process to also trim the values which you should be doing anyway. So, here's my take:

 

$address = isset($_POST['address']) ? trim($_POST['address']) : '';
if(!preg_match("/[0-9]/", $address ))
{
    //Invalid
    echo "The value '$address' is invalid"; //Add this for debugging
}

 

Psycho thank you very much for the reminder.. It's appreciated. But what I posted is just the summary of the code.. There's actually more into that like trimming, mysql escape and etc.

 

Anyway, Thanks again and it will be for sure noted for future work  8)

 

 

 

 

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.