Empowering Your Laravel Application with Custom Validation Rules

waziridev

waziri ally amiri

Posted on November 8, 2023

Empowering Your Laravel Application with Custom Validation Rules

Hello, fellow Artisan!
Laravel's validation system is known for its comprehensive set of built-in rules that ensure data integrity and user input correctness. However, there are cases where these built-in rules might not cover your specific validation requirements. This is where custom validation rules step in, allowing you to tailor the validation process to your unique needs.

Creating Custom Validation Rules
To define a custom validation rule in Laravel, you'll need to use a special Laravel Artisan command called php artisan make:rule. Let's illustrate this with an example. Suppose you have an attribute called start_date in your Laravel validation attributes, and you want to ensure that this date is either today or in the future, but not in the past. Since Laravel doesn't provide a built-in rule for this, you can create a custom validation rule.

To create your custom rule, run the following Artisan command:

php artisan make:rule StartDateBeforeToday
Enter fullscreen mode Exit fullscreen mode

This command generates a Laravel class named StartDateBeforeToday, which extends the ValidationRule interface and includes a validate method. Here's what the class might look like:

namespace App\Rules;

use Carbon\Carbon;
use Closure;
use Illuminate\Contracts\Validation\Rule;

class StartDateBeforeToday implements Rule
{
    public function validate($attribute, $value, $fail)
    {
        if (!(Carbon::parse($value)->isToday() || Carbon::parse($value)->isFuture())) {
            $fail('The :attribute must be a date that is today or in the future.');
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Inside the validate method, you can implement your custom validation logic. In this case, we're using the Carbon library to check if the date is today or in the future. If the validation fails, we call $fail with the error message we want to display to the user.

Using Your Custom Validation Rule
Now that you've created your custom validation rule, you can use it in your Laravel application. Here's an example of how to incorporate the StartDateBeforeToday rule into your validation logic:

$this->validate([
    'item.name' => ['required', 'string', 'max:255'],
    'item.slug' => [
        'required', 'string', 'max:255',
        Rule::unique('exams', 'slug')->ignore($this->exam->id)->whereNull('deleted_at')
    ],
    'item.description' => ['nullable', 'string'],
    'item.start_date' => ['required', 'date', new StartDateBeforeToday],
    'item.end_date' => ['required', 'date', 'after_or_equal:item.start_date'],
]);
Enter fullscreen mode Exit fullscreen mode

In the validation array, you can see how we apply the StartDateBeforeToday rule to the item.start_date attribute. Laravel will automatically invoke your custom validation rule when validating the data, ensuring that the start_date is either today or in the future.

Custom validation rules empower you to extend Laravel's validation capabilities to meet your specific requirements, making your application more robust and user-friendly.

Happay Coding!


About the Author
Hi there, I'm a Full Stack Developer based in Tanzania with a passion for Laravel, Livewire, VueJs, TailwandCss, and web development. As a freelancer, I'm always ready to take on exciting projects and collaborate on remote work related to Laravel.

If you're looking for a dedicated Laravel developer who can help you bring your web application to life or enhance your existing Laravel project, feel free to reach out to me. I'm eager to work with you to create robust and innovative solutions for your business needs.

You can contact me at [wazirially1994@gmail.com] or connect with me at [https://github.com/WAZIRI123] and WhatsApp via:[+255653039317].

Let's turn your Laravel project into a success story together!

💖 💪 🙅 🚩
waziridev
waziri ally amiri

Posted on November 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related