How To Register Custom Validation Rule in Laravel 8

Reading Time: 5 minutes
6,184 Views

Inside this article we will see the concept to register custom validation rule in laravel 8. Article contains classified information about custom rules in laravel 8.

If you are looking for an article which helps you to understand about custom validation rules in laravel 8 then you are right place to get the concept.

Laravel 8 by default provides many validation rules to validate user inputs either for string value, integer value, etc. But in several cases we need custom rules. In this tutorial we will register validation rule.

Learn More –

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Create Controller

Open project into terminal and run this artisan command.

$ php artisan make:controller CustomFormController

It will create CustomFormController.php file inside /app/Http/Controllers folder.

Open CustomFormController.php and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CustomFormController extends Controller
{
    // form view
    public function myform()
    {
        return view('myform');
    }
  
    // form submit function
    public function formSubmit(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|is_odd_string',
        ]);
        dd('Form Submitted');
    }
}

required is defined rule in laravel, is_odd_string is custom validation rule.


Add Routes

Open web.php from /routes folder. Add these routes into it.

use App\Http\Controllers\CustomFormController;

//...

Route::get('my-form', [CustomFormController::class, "myform"]);
Route::post('form-submit', [CustomFormController::class, "formSubmit"]);

//...

Register Custom Validation Rule

We will register is_odd_string custom validation rule.

Open AppServiceProvider.php from /app/Providers folder.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('is_odd_string', function ($attribute, $value, $parameters, $validator) {
            if (!empty($value) && (strlen($value) % 2) == 0) {
                return true;
            }
            return false;
        });
    }
}

We have registered custom validation rule in boot() method.


Add Validation Messages for Custom Rules

Open validation.php from /resources/lang/en folder.

Add key value pairs for messages for custom validation rules.

<?php

return [
  
  //...
  
  'is_odd_string' => "The :attribute must contains string of even length.",
  
];

Create Blade Template

Create view layout file myform.blade.php inside /resources/views folder.

<html lang="en">

<head>
    <title>Custom Validation Rule in Laravel 8</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <h4>Custom Validation Rule in Laravel 8</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Custom Validation Rule in Laravel 8</div>
            <div class="panel-body">
                <form action="{{ URL::to('form-submit') }}" class="form-horizontal" method="post">
                    @csrf
                    @if (count($errors) > 0)
                        <div class="alert alert-danger">
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif
                    <label for="">
                        Add Even String:
                    </label>
                    <input type="text" name="title" class="form-control" style="width:30%"
                        placeholder="String having even length" />
                    <br />
                    <button class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</body>

</html>

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/my-form

Submit form without any value

Submit form with odd string length

We hope this article helped you to Learn How to Register Custom Validation Rule in Laravel 8 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more