Laravel 8 - Simple Custom Validation Rules Example
Tags: laravel, php, mysql
Published: 2022-03-25 05:02:47

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

[![Advanced Laravel SAAS Starter Kit with CRUD Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyjyev8tz3r8vi2w3on1.png)](https://1.envato.market/5g5QAn)

[Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!](https://1.envato.market/5g5QAn)

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](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/laravel-8-simple-custom-validation-rules-example-B1sgYp7Lhmx980.webp?ctm=1630326961)

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
php artisan make:controller CustomValidationController
```

## Step 2: Create routes for custom validation rules

Below are the sample routes or our custom validation rules:

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

## 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
php artisan make:request InfoRequest
```

## Step 4: Create our controller methods

See below our custom validation rules controller methods

```php
<?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
    }
}
```

## Step 5: Creating our views

See my sample view below:

```php
@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
```

##Step 6: Adding validation rules and custom rules

**First,** run the following command below:

```php
php artisan make:rule BirthYearRule
```

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

```php
<?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').'.';
    }
}
```

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

```php
<?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()
            ]
        ];
    }
}
```

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.

[![Advanced Laravel SAAS Starter Kit with CRUD Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyjyev8tz3r8vi2w3on1.png)](https://1.envato.market/5g5QAn)

[Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!](https://1.envato.market/5g5QAn)

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 :)