How to Create Custom Validation Rules in Laravel 13
To create a custom validation rule in Laravel 13, run php artisan make:rule , implement the validate() method of the ValidationRule interface, call $fail() when the value is invalid, and add the rule object to your rules array. For one-off checks, a closure with the same signature works without a new class. What do you need before you start? Laravel 13 on PHP 8.3 or newer A form request or…
Creating custom validation rules in Laravel 13 involves running php artisan make:rule to generate a new rule class. This class must implement the ValidationRule interface and include a validate() method. The validate() method takes three parameters: $attribute (attribute name), $value (input value), and $fail (closure to store error messages).
To write the rule logic, first check if the input value is a string and meets the minimum length requirement. Then verify the value does not start with a digit and contains only letters, numbers, and underscores. If any condition fails, call $fail() to add an error message to the validation errors.
In a form request, use the custom validation rule by creating an array with the attribute name and the rule instance. For a closure rule, it can be used in place of a class and has the same signature. Place built-in validation rules like required before the custom rule to ensure the input meets basic criteria before running the custom logic.
To access other fields during validation, implement either DataAwareRule or ValidatorAwareRule interfaces and define the corresponding methods (setData() or setValidator()). These methods receive the validated data or validator instance, respectively, allowing the rule to access additional field values.
To handle translations, use the translate() method on the object returned by $fail() when creating an error message. This allows the error message to be translated using a language file key. Finally, to verify the custom rule works as expected, write a feature test that posts both valid and invalid input and checks for the expected error messages in the session.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.