phpvalidationfilter-var

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;

Solution

  • 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