The way of form validation in Laravel 10 using a custom rule is a bit different from the other lowest versions. In Laravel 10, the validation rule class provides us with only one method and that is validate() method. Using this method, we can validate form data. And of course, that rule is reusable. That means you can use this validation rule where you need to. 

In this tutorial, we will see how to create a custom validation rule in Laravel 10 and how to validate a specific field using a custom validation rule in Laravel 10. For this demo purpose, I will validate the email field using the custom validation rule in Laravel 10. Let's see the example code of the Laravel 10 custom validation rule example.

laravel-10-form-validation-with-custom-rule

Step 1: Create Validation Rule

There is an artisan command to generate a validation rule in Laravel 10 and that is 'make:rule'. So create a custom email validation rule like below:

php artisan make:rule EmailValidation

 

Now update the file like the below:

app/Rules/EmailValidation.php

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class EmailValidation implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $fail('The email format is invalid.');
        }
    }
}

 

Now use it in your controller like

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Rules\EmailValidation;
use Illuminate\Http\Request;

class TutorialController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => ['required', new EmailValidation]
        ]);

        Employee::create($request->except('_token'));

        return redirect()->route('employee.index')
            ->withSuccess('Employee has been created successfully.');
    }
}

 

Read also: Laravel 10 Validate Any Type Of File Example

 

Conclusion

Now we know laravel 10 custom validation rule. Now we know How to make a custom validation rule in Laravel 10. Hope this laravel 10 custom validation rule example tutorial will help you. After completing laravel 10 validation rules, your concept will be clear about laravel 10 custom form validation rule.