Frontend Validation with Laravel Requests – JsValidation

Today I’m introducing a great (actually awesome) package for Laravel. This package allows us to validate Laravel forms using the Validation rules we define in Request files, from the frontend. Yeah you heard me correct! This package (Laravel JsValidation) totally simplifies Frontend Form Validation for Laravel. Let’s get started!

Getting started!

Ok, I’m going to be so short and simple so that I’m just sticking to the point. To complete this tutorial, you need to have:

 

Install laravel-jsvalidation

Firstly, we need to install laravel-jsvalidation package from Github. To install this package to our Laravel installation, add the following line to your composer.json file.

proengsoft/laravel-jsvalidation:>2.2.0
{
    "require": {
        "laravel/framework": "5.6.*",
        ...
        "proengsoft/laravel-jsvalidation": ">2.2.0"
    },
    ...
    "scripts": {
        "post-update-cmd": [
            ....
            "php artisan vendor:publish --provider=\"Proengsoft\\JsValidation\\JsValidationServiceProvider\" --tag=public --force"
        ],
    },
}

Then run the composer update command on the terminal tto install the package.

$ composer update

Then run the following Artisan command to publish the package

$ php artisan vendor:publish --provider="Proengsoft\JsValidation\JsValidationServiceProvider"

And you may want to chanage the Bootstrap version of JsValidation since Laravel in currently using Bootstrap 4. Edit the followtin line in the config/jsvalidation.php

'view' => 'jsvalidation::bootstrap4'

Alight! now let’s do the coding.

Basic Usage

Then add the following lines of code to the at the bottom of the blade file containing the form.  And make sure you add an ID to the form.

<!-- Laravel Javascript Validation -->
<script type="text/javascript" src="{{ url('vendor/jsvalidation/js/jsvalidation.js')}}"></script>
{!! JsValidator::formRequest('App\Http\Requests\MyFormRequest', '#MyFromID') !!}

Cool. Now all you need to do is to create a Laravel Request and add some validation rules according to the from you created.

public function rules()
{
    return [
        'username' => 'required',
        'password' => 'required',
    ];
}

Now properly use this request in the controller method that is supposed to be called on the form submission. I’m not going to explain to that far. I believe you already know that.

So, that’s it. Try hitting submit button of the form with some invalid data, you may see your Laravel request validation rules does the job from the frotend too.

Frondend Validation with Laravel Requests

Isn’t this awesome? Thanks for stopping by!

Leave a Reply

Your email address will not be published. Required fields are marked *