Laravel 9 Custom Validation Rules Example


Share:
 | Published By: Admin | Published On: May 14, 2022 | Category: Laravel 9


Hello Artisan,

Today, In this article I am going to show you examples of custom validation rules. this example will help laravel 9 create a custom validator example.

In this tutorial, I will explain how to laravel 9 the custom validator rules. You can easily use make create your own custom validation rule with implement your own logic.

So, you can use this tutorial code and you can implement your laravel project.

Here, I will show you a full example of creating your own custom validation rule pad in laravel 9 so follow mine below steps.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: Create Custom Validation Rule

First of all we will create a custom validation rule following command.here i will use check number field is must be even.

php artisan make:rule CheckOddEvenRule
app/Rules/CheckOddEvenRule.php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CheckOddEvenRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

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

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The: attribute must be even value.';
    }
}
Step 3: Create Route

In this second step, we are doing it from scratch so we will add two routes, one for a show from the pad and another for store form. So you have to simply add two new routes in your laravel application.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('form/create',[HomeController::class,'index'])->name('form.create');
Route::post('form/store',[HomeController::class,'store'])->name('form.store');

Step 4: Create Controller
php artisan make:controller HomeController

In third step, we will create new HomeController file to handle request of created two new route. In this Controller we define two method, index() and store(). Both method will handle route request. So let's create new controller and put code.

app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Rules\CheckOddEvenRule;

class HomeController extends Controller
{
    /**
     * Write Your Code...
     *
     * @return string
    */
    public function index()
    {
        return view('myForm');
    }

    /**
     * Write Your Code...
     *
     * @return string
    */
    public function store(Request $request)
    {
        $input = $request->validate([
            'name' => 'required',
            'number' => [
                'required',
                new CheckOddEvenRule()
            ]
        ]);

        dd("You can proceed now...");
    }
}
Step 5: Create Blade File

In last step we will create myForm.blade.php following folder.

resources/views/myForm.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Custom Validation Rules Example - MyWebtuts.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header bg-secondary text-white">
                        <h4>Laravel 9 Custom Validation Rules Example</h4>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="{{ route('form.store') }}" autocomplete="off">
                            {{ csrf_field() }}
                            <div class="form-group">
                                <label>Name:</label>
                                <input type="text" name="name" class="form-control" placeholder="Name">
                                @if ($errors->has('name'))
                                    <span class="text-danger">{{ $errors->first('name') }}</span>
                                @endif
                            </div>
                            <div class="form-group">
                                <label>Number:</label>
                                <input type="number" name="number" class="form-control" placeholder="Number">
                                @if ($errors->has('number'))
                                    <span class="text-danger">{{ $errors->first('number') }}</span>
                                @endif
                            </div>
                            <div class="form-group">
                                <button class="btn btn-success btn-submit">Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/form/create

It will help you...

Share: