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;
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
Use preg_match
$str = '0123456789';
if(preg_match('/^\d{10}$/', $str))
{
echo "valid";
}
else
{
echo "invalid";
}
You can use regex :
if (!preg_match('~^\d{10}$~', $value)) return false;
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With