Laravel 8 Custom Validation Rules Example

Oct 07, 2021 . Admin



Hello Artisan,

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

In this tutorial, I will explain how to laravel 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 so follow mine below steps.

Step 1: 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
Path : 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: 2 Add Route

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

Path : /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!
|
*/

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

Step: 3 Create 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.

Path : /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 4: Create Blade File

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

Path : resources/views/myForm.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 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 8 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>

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/form/create

It will help you...

#PHP #Laravel 8 #Laravel