How To Register Custom Validation Rule in Laravel 8

Share this Article
Reading Time: 5 minutes
340 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.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project.

If your system doesn’t has composer Installed, Learn Composer Installation Steps.

Here is the complete command to create a laravel project-

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

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at 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

Open project to terminal and type the command 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.

Buy Me a Coffee

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.