ESC

Search on this blog

Weekly updates

Join our newsletter!

Do not worry we don't spam!

How To Validate Phone Numbers in PHP Photo:

How To Validate Phone Numbers in PHP


Collecting users' phone numbers is a common requirement in many PHP apps and web forms. Often you need to not only store these numbers but also verify if they are valid, properly formatted and safe to use in SMS/calls.

In this comprehensive guide, let's explore versatile techniques to validate national and international phone numbers in PHP applications.

 

Why Validate Numbers?

Typical reasons for validating any user-provided phone number include:

- Verify digits match a standard phone number format 
- Check a number belongs to the expected region/country
- Identify invalid fake/dummy numbers to avoid errors
- Prevent abuse by allowing only verified numbers  
- Auto-format numbers to assist calling and lookups

Invalid numbers can negatively impact communication-dependent features like account sign up, SMS notifications, 2FA authentication, phone verifications and calling integrations in your app.

Let's tackle common approaches to address these needs in PHP.

Using Regular Expressions

A regular expression (regex) allows defining a search pattern for matching strings in PHP. This powerful text processing capability makes regexes ideal for validating input.

Here is an example regex validating US numbers:


$number = '2015555555';
$regex = '/^(\d{3})-\d{3}-\d{4}$/';
if (preg_match($regex, $number)) {
 // Valid 
} else {
 // Invalid
}

This checks:

- Exactly 3 digits 
- Followed by a dash
- Followed by 3 more digits 
- Followed by another dash
- Followed by 4 digits

Matches indicate the input contains a properly formatted phone number.

But building robust regexes covering intricacies across global number formats is challenging. Instead we can leverage dedicated PHP libraries.


READ ALSO:


Using Validation Libraries

Specialized PHP libraries like `giggsey/libphonenumber-for-php` and `giggsey/locale` make phone validation easy without complex regular expressions.

Install them via Composer:

bash
composer require giggsey/libphonenumber-for-php
composer require giggsey/locale

Basic usage:


$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
try {
 $swissNumber = $phoneUtil->parse('044 668 18 00', 'CH');
 var_dump($phoneUtil->isValidNumber($swissNumber)); // bool(true)
} catch (libphonenumber\NumberParseException $e) {
 // Number could not be parsed 
}

We first configured the Switzerland (CH) country code to match against. This automatically detects if the number is valid for the region.

The `parse()` method returns a `PhoneNumber` object we can further assess and extract data from.

Let's break down key features available:

Check Validity

The `isValidNumber()` method determines if a parsed number matches expectations for country/region format:  


$phoneUtil->isValidNumber($swissNumber); 

Returns a boolean indicating validity. This accounts for differences like leading zeros in Europe vs North America.

Identify Country

Detect the country a number belongs to based on country code:


$countryCode = $phoneUtil->getRegionCodeForNumber($swissNumber);
// CH

Useful for selectively applying region specific validation rules.

Formatting Numbers

Format numbers to global or national conventions:



$phoneUtil->format($swissNumber, \libphonenumber\PhoneNumberFormat::INTERNATIONAL);
// +41 44 668 18 00
$phoneUtil->format($swissNumber, \libphonenumber\PhoneNumberFormat::NATIONAL);  
// 044 668 18 00

Great for displaying uniform numbers in your application UI.

Parsing User Input

Extract valid phone numbers from free-form user input strings like:



$possibleNumber = "Call me at 044 668 18 00 or +41 79 123 45 67!";
$phoneUtil->parseAndKeepRawInput($possibleNumber, "CH");  
// 0446681800 

Auto strips out only valid numbers from text/documents.

So in summary - these libraries take care of number validation/conversion logic behind the scenes using official libphonenumber database powering Google's implementations.

When to Validate?

Having explored capabilities, when should you actually attempt validation during your app workflows?

1. In HTML Input Fields: Browser validation constraints like type="tel" trigger phone keyboards and format hints on mobiles. Client-side validation catches simple issues before submitting the form.  

2. During Server-Side Validation: More thorough PHP validation should occur before processing and storage to prevent invalid data from entering databases.

3. Before Critical Communication: Just before triggering SMS, calls or 2FA checks - perform an additional validation to minimize errors reaching external services.

Follow these best practices and your users will thank you through higher engagement minus hiccups!

Conclusion

Validating phone numbers is crucial for many web and mobile applications. Using PHP validation libraries we can easily verify if a number matches expected country patterns quickly without complex regular expressions.

Additionally they enable reliably extracting, sanitizing and formatting telephone numbers from raw user input. What validation approaches have worked for your projects? Share your tips below!

5 Must-Have Packages for Your Next Laravel Project
Prev Article
5 Must-Have Packages for Your Next Laravel Project
Next Article
Laravel vs. CodeIgniter: Choosing the Right PHP Framework for Your Project
Laravel vs. CodeIgniter: Choosing the Right PHP Framework for Your Project

Related to this topic: