-2

I want to validate users phone numbers when they register in my website. I use this code to do this :

        $mobile = mysql_real_escape_string($_POST['mobile']);
        //check mobile validity
        $options = array('options' => array('min_range' => 0));
        if(filter_var($mobile, FILTER_VALIDATE_INT, $options) == FALSE)
        {
            $_SESSION['warnings']['warning_mobile'] = ENTER_VALID_MOBILE;   
        }
        else
        {
            $_SESSION['warnings']['warning_mobile'] = '';
            $_SESSION['temp_post']['mobile'] = $mobile;
        }

As you can see the code check if this number contains valid int digits and if it is everything going ok if not it give me error message .

My problem is : This code does not accept numbers which starts with zero for example (0 555 555 5555 this is invalid number).

Is there a way to allow this code to accept this numbers starting with zero??

  • 4
    Why do you want a solution that doesn't use regular expressions? – rr- Oct 21 '14 at 12:40
  • 3
    Phone number as `int`? bad idea. what `int` is that: `+112323132 ext. 12 ask for John`? – Marcin Orlowski Oct 21 '14 at 12:40
  • 2
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – Jay Blanchard Oct 21 '14 at 12:41

1 Answers1

0

Leaving on a side the fact that with a regular expression you could solve this problem easily, there are a couple of things to consider:

  • $mobile is a string: filter_var($mobile, FILTER_VALIDATE_INT) will allways return false.
  • do you want to consider digits only or you need to support numbers containing characters such as spaces, hyphen and plus? e.g. "+1 23-4555-555"

If you need to support "plain numeric" only, take a look to is_numeric. It checks if a variable is a number or a string made only by digits.

About your question:

Is there a way to allow this code to accept this numbers starting with zero??

Your code doesn't work because $mobile is not an integer, and not because your number starts with 0.

The final suggestion still is to use a regexes, which are the optimal solution for this kind of problems.

Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63