Skip to main content
Tutorial Free

How to (Easily) Create a Custom Validation Rule

May 30, 2018
1 min read

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

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

[NEW] Building a Typical Laravel SaaS

10 lessons
1 h 27 min

How to Build Laravel 12 API From Scratch

28 lessons
1 h 21 min

Laravel 12 For Beginners: Your First Project

15 lessons
1 h 32 min

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.