How to (Easily) Create a Custom Validation Rule

Tutorial last revisioned on August 18, 2022 with Laravel 9
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:
php artisan make:rule OlympicYear
Laravel generates a file app/Rules/OlympicYear.php:
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class OlympicYear implements Rule
{

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}
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:
public function passes($attribute, $value)
{
    return $value >= 1896 && $value <= date('Y') && $value % 4 == 0;
}
Next, we fill in the error message to be this:
public function message()
{
    return ':attribute should be a year of Olympic Games';
}
Finally, how we use this class? In controller's store() method we have this code:
public function store(Request $request)
{
    $this->validate($request, ['year' => new OlympicYear]);
}
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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses