How to validate data with regex in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Regular Expressions (regex) provide a powerful way to validate data by matching text against a pattern. In Laravel, using regex for validation ensures that the data conforms to a predefined format before it is ever processed by the application, enhancing both security and data integrity. In this tutorial, we’ll learn how to use regex for validation within Laravel, progressing from basic to more advanced examples.

Before delving into code examples, make sure you have a running Laravel application and are familiar with creating forms and validation requests within it.

Basic Regex Validation

The simplest way to implement regex validation in Laravel is by using the built-in validate method. Let’s validate a simple alpha-numeric string.

public function store(Request $request)
{
    $validatedData = $request->validate([
        'username' => ['required', 'regex:/^[A-Za-z][A-Za-z0-9]{5,31}$/'],
    ]);
    // The rest of the function...
}

The regex pattern /^[A-Za-z][A-Za-z0-9]{5,31}$/ ensures that the username starts with a letter and is between 6 to 32 characters long.

Custom Validation Messages

Sometimes, you may want to provide a custom message for regex validation failures. You can accomplish this by passing a second parameter to the validate method.

public function store(Request $request)
{
    $validatedData = $request->validate([
        'username' => ['required', 'regex:/^[A-Za-z][A-Za-z0-9]{5,31}$/'],
    ], [
        'username.regex' => 'The username must start with a letter and be alphanumeric.',
    ]);
    // The rest of the function...
}

If the validation fails, Laravel will now use the custom message instead of the default one.

Using Rule Objects

In more complex situations, using the Rule class to create custom validation rules can make our code more readable and maintainable.

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    public function passes($attribute, $value)
    {
        return preg_match('/^[A-Z]+$/', $value) > 0;
    }
    public function message()
    {
        return 'The :attribute must be all uppercase letters.';
    }
}

Then, you can use this rule like so:

$validatedData = $request->validate([
    'code' => ['required', new Uppercase],
]);

Advanced Regex Patterns

Now let’s test some more complicated patterns. For example, let’s validate an ISBN number which has a very specific format.

$validatedData = $request->validate([
    'isbn' => ['required', 'regex:/^(97(8|9))?\d{9}(\d|X)$/'],
]);

This pattern will validate both ISBN-10 and ISBN-13 formats.

Combining Regex with Other Rules

Regex validations can be combined with other Laravel validation rules to provide more context and control.

$validatedData = $request->validate([
    'email' => ['required', 'email', 'regex:/^.+@example\.com$/'],
]);

Here, we’re not only checking if the input is a valid email but also if it belongs to the example.com domain.

Handling Multiple Regex Conditions

When you have multiple regex conditions to validate, you can use arrays to cleanly separate each condition.

$validatedData = $request->validate([
    'password' => [
        'required',
        'regex:/[a-z]/',  // Must contain at least one lowercase letter
        'regex:/[A-Z]/',  // Must contain at least one uppercase letter
        'regex:/[0-9]/',  // Must contain at least one number
        'regex:/[@$!%*#?&]/', // Must contain a special character
    ],
]);

This ensures a robust password policy is enforced for user security.

Using Controllers and Form Requests

Laravel’s form request is a custom request class that includes validation logic. To demonstrate, let’s create one for signing up users that includes a regex condition.

php artisan make:request SignupRequest

Edit the generated SignupRequest class as follows:

public function rules()
{
    return [
        'name' => 'required',
        'email' => 'required|email|unique:users,email',
        'username' => 'required|regex:/^[A-Za-z][A-Za-z0-9]{5,31}$/',
    ];
}
public function messages()
{
    return [
        'username.regex' => 'The username must start with a letter and be alphanumeric.',
    ];
}

Now, you can use SignupRequest in your controller instead of the regular Request class, to handle validation logic.

Validating JSON Input

Validation isn’t limited to form data — you can also validate JSON requests. When working with an API that receives JSON data, use the validate method inside your controller’s method to enforce regex patterns.

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

This regex will validate international mobile phone numbers, with or without the country code.

Conclusion

Throughout this tutorial, we have explored various strategies for implementing regex-based validation in a Laravel application, ensuring data integrity and conformance to specified patterns. By understanding and utilizing the power of regex along with Laravel’s validation features, you can create robust and reliable applications that handle user input safely and efficiently.