Home > Mobile >  How to validate phone number with zero at the front in php?
How to validate phone number with zero at the front in php?

Time:01-26

I am validating phone numbers and this is my conditions,

if (!empty($phone)) {
    if (!filter_var($phone, FILTER_VALIDATE_INT) || !filter_var($phone, FILTER_VALIDATE_INT) === 0 || !is_numeric($phone) || !intval($phone)) {
        // Error msg
        // This segment working fine but
        // Its throwing error msg when I am using a mobile number starting with a zero
        // Like 01234567890
    } else {
        if (strlen($phone) > 16 || strlen($phone) < 8) {
            // Error msg
        } else {
            // Valid msg
        }
    }
} else {
    // Error msg
}

I want to through error msg if someone using 8 zeros or 16 zeros and I think its working but if someone using a valid phone number which is starting with a zero, then its throwing error msg as well.

How to pass number starting with a zero but mot all zeros?

CodePudding user response:

Employ the same classic lookahead technique that is commonly used for validating passwords.

Ensure that the phone is between 8 and 16 digits and has at least one non-zero.

Code: (Demo)

echo preg_match('/^(?=0*[1-9])\d{8,16}$/', $phone) ? 'Pass' : 'Fail';

Do not cast phone numbers as integers or store them as integers in a database if they can possibly start with a zero in your project.


Without regex, use an assortment of string function calls for the same effect. Demo

echo ctype_digit(ltrim($phone, '0')) && $length >= 8 && $length <= 16 ? 'Pass' : 'Fail';

CodePudding user response:

This additional check will ensure that the phone number does not consist of only zeroes.

if (!empty($phone)) {
        // Remove all non-numeric characters
        $phone = preg_replace("/[^0-9]/", "", $phone);
        // Check if the phone number is numeric and has a length between 8 and 16
        if (is_numeric($phone) && strlen($phone) >= 8 && strlen($phone) <= 16 && !preg_match('/^0 $/', $phone)) {
            // Valid msg
        } else {
            // Error msg
        }
    } else {
        // Error msg
    }
  • Related