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

How to validate a form in Laravel 8 with example ?

Aman Jain, October 4, 2021November 17, 2023

Laravel has inbuilt validation library to validate the input, post and get payload. Laravel has many validation like to validate the image, array, exist in database table, unique, regex etc. In this tutorial we are going to learn the validation on input for using Laravel validation library.

We will use simple Laravel validation required, max length, min length and email validation in this tutorial. Before starting this tutorial i assume you well know about the Laravel framework and the installation of it.

In this example we are using Laravel 8.

Let’s begin the tutorial with simple steps

Step 1 : Create Routes

First step is to create the routes to show the form and submit the form

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| 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']);

Step 2 : Create a controller

Now, create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController

Now, add use Illuminate\Support\Facades\Validator; and methods

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

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, Response $response)
    {
        $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',
        ]); // 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 added two methods one for to show the form view(create) and store to handle the form submit and validation.

Next, we have added validation for email, phone number and username. Email is required and should be format of email. Then, phone number should be required, numeric , digit_between 9 to 15.

Step 3 : Create the view for form

We have created routes and controller and now we need to create the form so we are creating the view file for it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Readerstacks laravel 8 form validation</title>
 <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
   </head>
    <body class="antialiased">
    <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>Laravel 8 form validation - Readerstacks</h3>
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form method="post" action="{{url('submit-post')}}" name="registerform">
             <div class="form-group">
                <label>Email</label>
                <input type="text" name="email" value="{{ old('email') }}" class="form-control" />
                @csrf
              </div>
              <div class="form-group">
                <label>Phone number</label>
                <input type="text" name="phone_number"  value="{{ old('phone_number') }}" class="form-control" />
              </div>
              <div class="form-group">
                <label>Username</label>
                <input type="text" name="username"   value="{{ old('username') }}" class="form-control" [ />
              </div>
            
              <div class="form-group">
                <button class="btn btn-primary">Register</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Laravel 8 form validation </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
    </body>
</html>

In the view file we have added bootstrap for better ui and error container and form

 @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
@endif

Screenshot

Screenshot 2021 10 04 at 10.08.15 PM
Laravel 8 validation

How to use validation error below the input field?

It’s better to show the error message below the input field for better user experience.

<form method="post" 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>

We have added @error and class="@error('email') is-invalid @enderror form-control" to show the error on individual field.

Screenshot 2021 10 04 at 10.31.05 PM
Laravel validation on each field

Related

Php Laravel

Post navigation

Previous post
Next post

Related Posts

Php How to Add Default Value to Column in Laravel Migration

How to Add Default Value to Column in Laravel Migration?

August 17, 2022March 16, 2024

Default value to column is useful when we want to auto fill the default defined value of column during insertion of other values of table So In our this article i will show you to add default value to column in laravel migration. We can add any type of data…

Read More
Javascript Laravel Ajax Autocomplete Using Select2

Laravel Customized Autocomplete Options Using Select2

July 18, 2022July 18, 2022

In this article we will learn to use Laravel Customized Autocomplete Options Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and…

Read More
Php Laravel 8 generate qr code

How to generate qr code in Laravel 8?

October 16, 2021November 16, 2021

In this article we will learn to generate the qr code in Laravel. we will use a simple example to generate the qr code. As we know qr code is stand for Quick Response and we can scan and get the information from it. we can use qr code in…

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