Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP filter validate int issue when first character is 0

I am using the PHP filter_validate_int to perform a simple telephone validation. The length should be exactly 10 chars and all should be numeric. However as most of the telephone numbers start with a 0. The filter validate int function return false. Is there anyway to resolve this issue. Here is the code that I have used

if(!filter_var($value, FILTER_VALIDATE_INT) || strlen($value) != 10) return false;
like image 445
codeGEN Avatar asked Sep 20 '13 08:09

codeGEN


4 Answers

There is nothing you can do to make this validation work. In any case, you should not be using FILTER_VALIDATE_INT because telephone numbers are not integers; they are strings of digits.

If you want to make sure that $tel is a string consisting of exactly 10 digits you can use a regular expression:

if (preg_match('/^\d{10}$/', $tel)) // it's valid

or (perhaps better) some oldschool string functions:

if (strlen($tel) == 10 && ctype_digit($tel)) // it's valid
like image 55
Jon Avatar answered Nov 16 '22 05:11

Jon


Use preg_match

$str = '0123456789';

if(preg_match('/^\d{10}$/', $str))
{
    echo "valid";
} 
else 
{
    echo "invalid";
}
like image 38
Vishnu Avatar answered Nov 16 '22 06:11

Vishnu


You can use regex :

if (!preg_match('~^\d{10}$~', $value)) return false;
like image 35
Glavić Avatar answered Nov 16 '22 06:11

Glavić


It's a PHP bug - #43372

Regex are fine, but consume some resources.

This works fine with any integer, including zero and leading zeros

if (filter_var(ltrim($val, '0'), FILTER_VALIDATE_INT) || filter_var($val, FILTER_VALIDATE_INT) === 0) {
    echo("Variable is an integer");
} else {
    echo("Variable is not an integer");
}
like image 1
migli Avatar answered Nov 16 '22 04:11

migli