Question

The function below checks if a string is an integer meaning it should only contain digits. But it does not check if number is negative (negative numbers should return true as well since they are integers).

function validateInteger($value)
{
   //need is_numeric to avoid $value = true returns true with preg_match
   return is_numeric($value) && preg_match('/^\d+$/', $value);
}

I ran tests and got results:

'12.5'      => FALSE 
12.5        => FALSE 
'a125'      => FALSE 
'125a'      => FALSE 
'1a2.5'     => FALSE 
125         => TRUE 
'abc'       => FALSE 
false       => FALSE 
true        => FALSE 
'false'     => FALSE 
'true'      => FALSE 
null        => FALSE 
'null'      => FALSE 
'1231'      => TRUE 
-1231       => FALSE (SHOULD RETURN TRUE)
'-1231'     => FALSE (SHOULD RETURN TRUE)

I dont want to use itnval() < 0. I would prefer regular expression to check for negative numbers as well.

Thanks

EDIT:

I also have a function validateFloat that returns true if a given number is floating number meaning it can contain only digits and a dot. I need to apply same logic to this as well so that it returns true for negative floating numbers

Was it helpful?

Solution 2

just use is_numeric(abs($val))

OTHER TIPS

is_int isn't good enough for you?

filter_var($input, FILTER_VALIDATE_INT) should have the same effect but also work on strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top