laravel rules validation

How to (Easily) Create a Custom Validation Rule

For some reason, only now I’ve found out about a feature that was introduced in Laravel 5.5 – artisan command that makes your validation rule, similar to Request classes. Let’s see it in action.

Let’s take an example of a form to fill in Summer Olympic Games events – so year and city:

laravel form

Now, let’s create a validation rule that you can enter only the year of Olympic Games:

  • Games started in 1896
  • Year can’t be bigger than current year
  • Number should be divided by 4

Let’s run a command:

Laravel generates a file app/Rules/OlympicYear.php:

As I said, it’s similar to Requests classes for validation. We fill in the methods. passes() should return true/false depending on $value condition, which is this in our case:

Next, we fill in the error message to be this:

Finally, how we use this class? In controller’s store() method we have this code:

Pay attention to syntax, second parameter should be an array and then we create a new object from our Rule class.
That’s it!

Laravel validation custom

Liked the article? Maybe you need help with your Laravel project?
Check out my Upwork profile and hire me!

5 thoughts on “How to (Easily) Create a Custom Validation Rule

  1. I think you got a code error in $this->validate($request, [‘year’ => new OddNumber]);
    should be $this->validate($request, [‘year’ => new OlympicYear]);

    Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *