DEV Community

Cover image for Laravel 8 - Simple Custom Validation Rules Example
codeanddeploy
codeanddeploy

Posted on

Laravel 8 - Simple Custom Validation Rules Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-simple-custom-validation-rules-example

In this post, I will share how to create simple custom validation rules on Laravel 8. Laravel provides out-of-box validations that help to fast our web application development. But sometimes we need to create our own validation that beyond the Laravel default that is suitable for our needs. So in my example in this post I will validate the inputted birth year and only accept from 1990 to the current year. If the user provides less than 1990 or more than the current year it will throw a validation error.

laravel-8-simple-custom-validation-rules

So I assume that you have your Laravel installed already so I skip the installation process and I will create my sample Controller.

Step 1: Create the controller

Run the following command to create a controller:

php artisan make:controller CustomValidationController
Enter fullscreen mode Exit fullscreen mode

Step 2: Create routes for custom validation rules

Below are the sample routes or our custom validation rules:

/**
* Custom validation routes
*/
Route::get('/custom-validation', 'CustomValidationController@show');
Route::post('/custom-validation', 'CustomValidationController@perform')->name('custom-validation');

Enter fullscreen mode Exit fullscreen mode

Step 3: Create a request

We need to create our request to call the custom validation rule next. Run the following command to do it.

php artisan make:request InfoRequest
Enter fullscreen mode Exit fullscreen mode

Step 4: Create our controller methods

See below our custom validation rules controller methods

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\InfoRequest;

class CustomValidationController extends Controller
{
    public function show() 
    {
        return view('test.custom-validation');
    }

    public function perform(InfoRequest $request) 
    {
        // Save after validated
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Creating our views

See my sample view below:

@extends('layouts.app-master')

@section('content')
    <div class="bg-light p-5 rounded">
        <h1>Laravel Custom Validation Rule by CodeAndDeploy.com</h1>

        <form method="post" action="{{ route('custom-validation') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}" />

            <div class="form-group form-floating mb-3">

                <div class="form-group">
                    <label>Full name</label>
                    <input type="text" 
                        name="name" 
                        placeholder="Name" 
                        class="form-control" 
                        value="{{ old('name') }}">
                    @if ($errors->has('name'))
                        <span class="text-danger text-left">{{ $errors->first('name') }}</span>
                    @endif
                </div>

                <div class="form-group mt-3">
                    <label>Birth Year</label>
                    <input type="number" 
                        name="birth_year" 
                        placeholder="E.g. 1990" 
                        class="form-control"
                        value="{{ old('birth_year') }}"
                        maxlength="4">
                    @if ($errors->has('birth_year'))
                        <span class="text-danger text-left">{{ $errors->first('birth_year') }}</span>
                    @endif
                </div>

            </div>

            <button class="w-100 btn btn-lg btn-primary" type="submit">Save</button>
        </form>
    </div>
@endsection
Enter fullscreen mode Exit fullscreen mode

Step 6: Adding validation rules and custom rules

First, run the following command below:

php artisan make:rule BirthYearRule
Enter fullscreen mode Exit fullscreen mode

Second, let's add custom rules to our BirthYearRule.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class BirthYearRule 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 $value >= 1990 && $value <= date('Y');
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be between 1990 to '.date('Y').'.';
    }
}
Enter fullscreen mode Exit fullscreen mode

Third, let's write our form validation from Laravel default and also our custom validation. See below for our complete code:

<?php

namespace App\Http\Requests;

use App\Rules\BirthYearRule;
use Illuminate\Foundation\Http\FormRequest;

class InfoRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'birth_year' => [
                'required',
                new BirthYearRule()
            ]
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see in the 'birth_year' array value we added a new BirthYearRule() class to call our custom validation rules.

Now, apply and run it.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-simple-custom-validation-rules-example if you want to download this code.

Happy coding :)

Discussion (0)