Spread the love

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

Laravel 8 custom form validation

Leave a Reply