Sling Academy
Home/PHP/PHP: 3 Ways to Validate a Phone Number

PHP: 3 Ways to Validate a Phone Number

Last updated: January 10, 2024

Solution 1: Using Regular Expressions

Regular expressions are a powerful tool for string processing which can be used to validate phone numbers. By defining a pattern, we can match phone numbers to different formats.

  • Define a regular expression pattern that fits the phone number format you expect.
  • Use the preg_match() function in PHP to test if the phone number matches the pattern.
  • Handle the result to proceed with valid inputs or provide an error for invalid inputs.

Example:

$pattern = '/^\+[1-9]{1}[0-9]{3,14}$/';
$phoneNumber = '+1234567890';

if (preg_match($pattern, $phoneNumber)) {
    echo 'Phone number is valid.';
} else {
    echo 'Phone number is not valid.';
}

Performance: Regular expressions can be fast, but complex patterns may lead to slower execution times.

Pros and Cons: Very flexible. Can be tailored to different formats. However, complex patterns can be hard to maintain and debug.

Solution 2: Using filter_var() Function

The filter_var() function is used to filter and validate data. It can validate various types of data, including phone numbers by loosely checking if the string contains numeric values.

  • Use the filter_var() function with the FILTER_SANITIZE_NUMBER_INT filter.
  • Check if the sanitized value has the length and composition of a phone number.
  • Proceed based on the validation result.

Example:

$phoneNumber = '+123-456-7890';
$sanitizedNumber = filter_var($phoneNumber, FILTER_SANITIZE_NUMBER_INT);

if (strlen($sanitizedNumber) >= 10) {
    echo 'Phone number is valid.';
} else {
    echo 'Phone number is not valid.';
}

Pros and Cons: Simple to implement, but only checks for numbers and sign purity, not for a specific format.

Solution 3: PHP Libraries

There are PHP libraries dedicated to data validation, such as libphonenumber for PHP, an implementation of Google’s libphonenumber library, specially apparent for validating phone numbers.

  • Install the PHP library via Composer.
  • Use the library to validate the phone number.

Example:

require_once 'vendor/autoload.php';
$phoneNumber = '+1234567890';
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
try {
    $numberProto = $phoneUtil->parse($phoneNumber, null);
    if ($phoneUtil->isValidNumber($numberProto)) {
        echo 'Phone number is valid.';
    } else {
        echo 'Phone number is not valid.';
    }
} catch (\libphonenumber\NumberParseException $e) {
    echo 'The number provided is not a valid format: ', $e->getMessage();
}

Pros and Cons: Provides a robust solution for validating international phone numbers with proper format. However, requires external dependencies and more knowledge to implement.

Conclusion

Validating phone numbers in PHP can be approached in multiple ways, each with its advantages and limitations. Regular expressions offer flexibility for custom formats, filter_var() allows basic validation with a single line of code, while PHP libraries offer the most comprehensive solution at the expense of adding external dependencies. Your choice should depend on the specificity of your requirements and the nature of your project.

Next Article: PHP: 3 Ways to Validate Credit Card Patterns

Previous Article: PHP: 4 Ways to Validate an IP Address

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array