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 set timezone dynamically and globally in Laravel

How to set timezone dynamically and globally in Laravel ?

September 20, 2022March 16, 2024

Laravel stores timezone configurations in config/app.php file and we can easily set timezone dynamically and globally in Laravel. Laravel usage carbon library to get the current date time and format, carbon also respects the timezone defined in config/app.php file. After php 5, php also introduced DateTime class to conduct the…

Read More
Php Understanding laravel request

Understanding Laravel request with example

November 17, 2021November 22, 2021

Laravel provides a own class to handle the request which is Illuminate\Http\Request. Request is used to retrieve the user input(GET and POST), cookies and files that was submitted during the request. Get the request in controller Current Request can be get retrieved in controller by injecting the dependency in controller…

Read More
Devops How to Install multiple versions of PHP?

How to Install multiple versions of PHP?

September 18, 2021September 21, 2021

Sometimes it’s required to install the different version of PHP rather then the default one of Ubuntu Repository System. To install the different version we will follow the basic steps before installation of PHP Step 1 : Add ppa:ondrej/php to Ubuntu system Open the terminal or ssh connection and then…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version