A Comprehensive Guide to Laravel Validation Rules: Validating Phone Numbers

Rajib Bin Alam
12 Aug 2024
5 mins to read
549 words
Share

Laravel, the elegant PHP framework, is known for its developer-friendly features. One of the standout features of Laravel is its robust validation system, which allows developers to easily ensure that incoming data meets specified criteria. Whether it's a simple string validation or a complex set of rules, Laravel makes it easy to validate data before processing it.

In this post, we'll delve into Laravel's validation rules, with a specific focus on validating phone numbers. We'll explore how to use the built-in validation methods, and how to create custom validation rules for more complex cases.

Laravel Validation: The Basics

Laravel provides a clean and fluent API for validation, making it easy to validate user input. The most common way to validate input is through the validate method provided by the Illuminate\Http\Request object.

Here’s a quick example:

 
public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'phone' => 'required|digits:10', // Phone number validation
    ]);

    // If the validation passes, continue to process the data
}

 

In this example, we're validating three fields: name, email, and phone. The phone field is being validated to ensure that it is exactly 10 digits long.

Commonly Used Validation Rules

Before we dive into phone number validation, let's quickly review some of the most commonly used validation rules in Laravel:

  • required: Ensures that the field is present in the request.
  • string: Ensures that the value is a string.
  • max: Specifies the maximum length or value for the field.
  • email: Validates that the value is a valid email address.
  • unique: Ensures that the value is unique in a specified database table.

Phone Number Validation in Laravel

Validating phone numbers can be tricky due to the variety of formats used around the world. Laravel provides several ways to validate phone numbers, from basic digit validation to more complex patterns.

Basic Phone Number Validation

The simplest way to validate a phone number is to check for a specific number of digits using the digits rule:

 

$validatedData = $request->validate([
    'phone' => 'required|digits:10',
]);

 

This validation ensures that the phone number is exactly 10 digits long, which is suitable for countries like the United States. However, phone numbers can vary significantly in length and format across different countries.

Advanced Phone Number Validation

For more complex validation, such as international phone numbers, you can use regular expressions. Laravel's regex rule allows you to validate the format of the phone number more precisely:

 

$validatedData = $request->validate([
    'phone' => ['required', 'regex:/^(\+\d{1,3}[- ]?)?\d{10}$/'],
]);

 

In this example, the regex rule ensures that the phone number can start with an optional country code (e.g., +1, +44) followed by exactly 10 digits.

Using Third-Party Packages

For even more advanced phone number validation, such as ensuring that the phone number is valid for a specific country or carrier, you can use third-party packages like Laravel Phone:

  1. Install the package:

     

    composer require propaganistas/laravel-phone

     

  2. Use the phone validation rule:

     
    $validatedData = $request->validate([
        'phone' => 'required|phone:US,CA', // Validates US and Canadian phone numbers
    ]);

     

    This package allows you to validate phone numbers for specific countries, formats, and even carriers.

Creating Custom Validation Rules

Sometimes, built-in rules or third-party packages might not cover your specific validation needs. In such cases, Laravel allows you to create custom validation rules.

Here’s how you can create a custom validation rule for phone numbers:

  1. Generate the custom rule:

     

    php artisan make:rule PhoneNumber

     

  2. Implement the rule:

    In the generated PhoneNumber.php file, you can define the validation logic:

     
    namespace App\Rules;
    
    use Illuminate\Contracts\Validation\Rule;
    
    class PhoneNumber implements Rule
    {
        public function passes($attribute, $value)
        {
            // Example: Validate that the phone number starts with a specific area code
            return preg_match('/^(\+1)?[2-9]\d{2}[2-9]\d{6}$/', $value);
        }
    
        public function message()
        {
            return 'The :attribute is not a valid phone number.';
        }
    }
     
  3. Use the custom rule in your controller:

     
    use App\Rules\PhoneNumber;
    
    $validatedData = $request->validate([
        'phone' => ['required', new PhoneNumber],
    ]);
     

    This custom rule checks if the phone number starts with a specific area code and has the correct number of digits.

 

Conclusion

Laravel's validation system is powerful and flexible, allowing you to validate data in a variety of ways. Whether you're using built-in rules, regular expressions, third-party packages, or custom rules, Laravel provides the tools you need to ensure that your data is valid before processing it.

Validating phone numbers, in particular, can be challenging due to the wide variety of formats used globally. However, with Laravel's validation features, you can handle both simple and complex phone number validations with ease.

With the ability to create custom rules, the possibilities are endless, ensuring that your application handles data validation exactly the way you need.

Happy coding!