Search code examples
phpvalidationpreg-matchphone-number

PHP Phone Verification


I have a problem with the registry, I want to do to verify 9 digits mobile.

Code:

$tel = $_POST['tel'];
$sdt_length = strlen($tel);
$sdt_check = substr($tel, 0, 2);
elseif (!preg_match("/^[0-9]*$/i", $tel))
elseif ( ($sdt_check == '09' && $sdt_length == 10) || ($sdt_check == '01' && $sdt_length == 11) ) {

Solution

  • Phone formats can differ greatly from region to region. I will assume that you are perfectly aware of the phone formats that you are dealing with and that they will not be POSTed with any kind of symbols.

    You need a 9 digit string or a 10 or 11 digit string depending on the first two digits: 09 or 01, use this:

    ^(?:09\d{8}|01\d{9}|\d{9})$
    

    See Demo

    The above pattern will check for digit-only strings and length based on the first two digits.

    PHP implementation:

    if(isset($_POST['tel']) && preg_match("/^(?:09\d{8}|01\d{9}|\d{9})$/",$_POST['tel'])){
        $tel=$_POST['tel'];
    }else{
        echo "Missing or Invalid Telephone Number";
    }