Laravel 5.4 - Validation with Regex

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company
Title: Laravel 5.4 - Validation with Regex Body:

In this blog post, we will explore how to create validation rules using regular expressions in Laravel 5.4.

Before moving forward, it is essential to understand that Laravel 5.4 has been end of life since August 2018 and no longer receives updates or bug fixes. For up-to-date solutions, we recommend using a newer version of the framework.

Validation with Regex in Laravel 5.4

Laravel provides robust validation functionality for input data. One way to define your validation rules is by using regular expressions. In our case, we want to ensure the project name starts with a letter from 'a-z' or 'A-Z' and can be followed by numbers but not both together. Let's take a look at an example:
$this->validate(request(), [
    'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];
The regex rule for this example is as follows:

(?P<StartLetter[a-zA-Z]*).(?P<Numbers>\d*)?(?=(\d+)?$)(?>\1[\3\d]*(?=\1))

This rule is broken into four parts: 1. (?P[a-zA-Z]*). This part captures the initial letter, ensuring it's a valid letter from 'a-z' or 'A-Z'. The "." stands for any character, but this will be anchored by parentheses and we are explicitly setting its range to only letters. 2. (?P\d+)?$. This part defines that the input can end with either zero or more numbers. We use "\d+" which represents one or more digits, and "?" to make it optional. The $ symbol at the end ensures a full match. 3. (?>\1[\3\d]*(?=\1))$. This part ensures that there are no trailing letters before the numbers. If there were any trailing letters, it would not be a valid input according to our requirements. The "\\1" represents the value captured by and \3 represents "Numbers".

Note: This approach might look slightly complex but using these advanced regular expressions can efficiently validate user inputs based on specific criteria.

To verify this rule, we can use a regex testing tool like https://regex101.com/r/FylFY1/2. Here's the link we mentioned in our original question: https://regex101.com/r/FylFY1/2

Additional Resources and Best Practices

For more in-depth understanding of regular expressions, you can refer to Laravel's documentation: https://laravel.com/docs/5.6/validation#rule-regex To better understand the rules and syntax of regular expressions, visit this handy guide: https://www.regular-expressions.info/ In summary, validating user inputs with advanced regex rules in Laravel 5.4 can ensure that your application data is clean and consistent. However, make sure to test these rules thoroughly before using them live as they can be error-prone if not tested properly. For more recent versions of Laravel, it is recommended to use the latest documentation and resources provided by the framework.