Laravel 9 How To Register Custom Validation Rule

Share this Article
Reading Time: 5 minutes
662 Views

Inside this article we will see the concept i.e Laravel 9 How To Register Custom Validation Rule. Article contains classified information about custom rules in laravel 9.

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

Laravel 9 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

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

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 a 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 added custom validation rule in boot() method.

Add Validation Messages for Custom Rules

Open validation.php from /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 9</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 9</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Custom Validation Rule in Laravel 9</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 Laravel 9 How to Register Custom Validation Rule Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5