Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
laravel custom validation

How to make custom validation in Laravel 8 ?

Aman Jain, October 19, 2021October 28, 2021

In this tutorial we will learn to implement custom validation rule in Laravel 8. Laravel has too many validation rules but sometime we feel some rules are missing according to our project need. so, in this article we will learn to implement custom reusable validation rule and implement the username validation which will only accept letters and hyphen in the rule.

Let’s begin the tutorial with simple steps:

Step 1: Create Laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2: Create new rule for validation

Now, we will create a rule class for our custom validation using the Laravel artisan command.

php artisan make:rule Alphahypen

Above command will create a class Alphahypen in folder app\Rules. Alphahypen class implement the interface Rule which required two methods passes and message.

passes method accepts two parameters attribute value and name, return type of passes method is boolean which means true and false.

message method return message of validation if the validation rule fail.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Alphahypen 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)
    {
        return preg_match('/^[\pL\-]+$/u', $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'This field only accept letters and hypen.';
    }
}

So, here we added return preg_match('/^[\pL-]+$/u', $value); in passes method to check the value is only accepting letters and hypen.

Step 3: Create controller

Create a new controller to test the new rule using artisan n command.

php artisan make:controller PostController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Rules\Alphahypen;

class PostController extends Controller
{

     /**
     * Show the form to create a new blog post.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',   // required and email format validation
            'phone_number' => 'required|numeric|digits_between:9,15', // required and number field validation
            'username' => ['required',new Alphahypen],
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
              
            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form

        }
        else
        {
            //handle the form 
        }  
    }
     
}

Here, we imported the new rule class use App\Rules\Alphahypen; and 'username' => ['required',new Alphahypen], used Alphahypen here.

Step 4: Create blade file for view

Now it’s time to show the form and validation message to our view, so let’s create the view file.

 <h3>Laravel 8 custom form validation - Readerstacks</h3>

            <form method="post" id="validateajax" action="{{url('submit-post')}}" name="registerform">
              <div class="form-group">
                <label>Email</label>
                <input type="text" name="email" value="{{ old('email') }}" class="@error('email') is-invalid @enderror form-control" />

                @error('email')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                @csrf
              </div>
              <div class="form-group">
                <label>Phone number</label>
                <input type="text" name="phone_number" value="{{ old('phone_number') }}" class="@error('phone_number') is-invalid @enderror form-control" />
                @error('phone_number')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
              </div>
              <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" value="{{ old('username') }}" class="@error('username') is-invalid @enderror form-control" />
                @error('username')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
              </div>

              <div class="form-group">
                <button class="btn btn-primary">Register</button>
              </div>
            </form>

Step 5: Create routes

Now, open the routes/web.php and add below routes

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;
use \App\Http\Controllers\QRController;

/*
|--------------------------------------------------------------------------
| 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('/create-post',[PostController::class, 'create']);
Route::post('/submit-post',[PostController::class, 'store']);

Check our final code by open the url in browser

Screenshot 2021 10 19 at 11.01.29 PM
Laravel 8 custom form validation

Related

Php Laravel

Post navigation

Previous post
Next post

Related Posts

Php How to ShareSend Message to WhatsApp in Laravel PHP

How to Share/Send Message to WhatsApp in Laravel PHP ?

March 16, 2022March 16, 2022

Sharing or sending message to whatsapp from a website using a link is simple as possible. In this article we will not use any package or third party tool to share the url or message to whatsapp. Whatsapp itself provide to share or send message using the url so in…

Read More

Laravel array validation with example

December 15, 2021November 12, 2023

In this tutorial i will explain to use validating a array inputs using Laravel validation library. Laravel also supports to validate group of array and we can validate a array same as normal input. In our recent article Laravel form validation how to validate a form and files. In this…

Read More
Php Extract/Unzip a Zip File in Laravel

How to Extract/Unzip a Zip File in Laravel ?

May 22, 2022November 5, 2023

In laravel Extract/Unzip zip a file can be achieved by ZipArchive library,its gives easy to use flexibilities to developers so they can easily Extract/Unzip a Zip File in Laravel and integrate the Zip creation activity in the project. Zip files are used to create lossless data compression and store multiple…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version