سؤال

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

هل كانت مفيدة؟

المحلول 2

just use is_numeric(abs($val))

نصائح أخرى

is_int isn't good enough for you?

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top