Learning Management Platform for Written Tutorial Series.

Laravel 6 Validation

Laravel 6 Validation

Validation is the process of checking whether the submitted data adheres to the defined rules governing the processing of that data. For example, if a user submits an email address, then we expect that email address to be valid. If the @ symbol is missing from the submitted email address, then the submitted value does not adhere to the defined rules of what is acceptable as an email address. If the submitted input meets all the defined rules for an acceptable email address, then it is accepted as a valid email address.

Laravel 6 Validation

In this tutorial, we will look at various validation types and how we can perform validation using Laravel.

Topics to be covered

In this tutorial, we will cover the following topics

  • Importance of data validation
  • Types of data validation
  • Validation Rules & Messages

Importance of data validation

The following are some of the advantages of data validation

  • Incorrect data types can break the application -- let's say you are developing an inventory system application and you need to compute the total amount and a numeric output value is expected. If a user submitted the letter g instead of a numeric value, then this can cause an exception to be thrown
  • Ensures required data is available -- the application needs to process input to process it into output. Validation ensures that all the required input is available before proceeding to the processing.
  • Provides application security -- the data that users provide usually goes to the database. It's possible malicious users can inject harmful code which can result in elevated user access to data loss. Validation prevents such from happening.

Types of data validation

The following are some of the common data validation types

  • Required -- this rule ensures that the required data has been submitted before processing. If its absent, then an error is returned instead.
  • Data type validation -- it's very common to define multiple validation rules for a single field. For example, if a user is registering for an account, the required rule is not enough, we also need to make sure the value submitted is a valid email address.
  • Range check -- if we have an application that needs the accept the number of days in a week then its only logic to limit the days of the week between 1 and 7. Allowing a value like 9 would result in an invalid range.
  • Unique -- some data just needs to be unique; we wouldn't want to have two people with the same email account. So, we cross check the existing records with what is submitted. If it's not unique then we return a duplicate value validation error.
  • Exists -- if say a user forgot a password and what's to receive a reset password email, then we need to check if to see if the submitted email address is valid.

The above list is not exhaustive but lists some of the common rules that we will have to work with in Laravel applications.

Laravel Validation Rules and Messages

Let's create a new project and learn how to validate user input in Laravel.

Run the following command to create a new project

composer create-project laravel/laravel validation 6.0.*

HERE,

  • The above command creates a new Laravel project using latest version of Laravel 6.0

We will now create a simple HTML form that simulates user registration on a website. Our form will be will be able to accept the following parameters and validation rules

  • Username - this is a mandatory field and it should not contain any spaces. The datatype is alphanumeric
  • Email - this is a mandatory field and it should be a valid email address.
  • Password -- this is a mandatory field.

Let's now create an HTML form that will accept input from the user.

Create a new directory users in /resources/views

Create a new file create.blade.php in the directory /resources/views/users

Add the following code to create.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{$title}}</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="{{asset('css/style.css')}}" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-6">
                        <h2>User <b>Registration</b></h2>
                    </div>
                </div>
            </div>
            <form action="{{route('users.create')}}" method="POST">
                @csrf
                <div class="form-group {{ $errors->has('username') ? ' has-error' : '' }}">
                    <label for="username">Username</label>
                    <input class="form-control" name="username" value="{{Request::old('username')}}" placeholder="Enter username" type="text">
                    @if ($errors->has('username')) 
                    <span class="help-block">{{ $errors->first('username') }}</span>
                    @endif
                </div>
                <div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
                    <label for="email">Email</label>
                    <input class="form-control" name="email" value="{{Request::old('email')}}" placeholder="Enter email" type="email">
                    @if ($errors->has('email')) 
                    <span class="help-block">{{ $errors->first('email') }}</span>
                    @endif
                </div>
                <div class="form-group {{ $errors->has('password') ? ' has-error' : '' }}">
                    <label for="email">Password</label>
                    <input class="form-control" name="password" placeholder="Enter password" type="password">
                    @if ($errors->has('password')) 
                    <span class="help-block">{{ $errors->first('password') }}</span>
                    @endif
                </div>
                <button class="btn btn-success" type="submit">
                    <i class="fa fa-save"></i> Register
                </button>
            </form>         
        </div>
    </div>     
</body>
</html>                                                                 

HERE,

  • <form action=\"{{route(\'users.create\')}}\" method=\"POST\"\> opens the form element, sets the action method to the named route users.create and sets the form method to POST
  • \@csrf sets the CSRF token using a blade directive
  • `<div class="form-group {{ $errors->has('username') ? ' has-error' : '' }}">` users a conditional construct to check if the errors array has an element of username. If the condition is true then the class has-error is appended to the div else nothing is appended to the class.
  • <input class="form-control" name="username" value="{{Request::old('username')}}" placeholder="Enter username" type="text"> defines the input control for the username name that is also named username. value="{{Request::old('username')}}" is used to preserve the value that was supplied for the particular input before submitting to the server for validation. For example, if a user enters a valid username but supplies an invalid password, then the previously supplied username will be preserved in the form. Without this, the user will be required to fill in all the input controls again even for fields that passed validation.
  • @if ($errors->has('username'))... @endif checks if the error array contains any element named username then displays the error message using <span class="help-block">{{ $errors->first('password') }}</span> if the condition evaluates to true.

Let's now create a controller that will respond to our actions

Open the command line / terminal

Run the following command

php artisan make:controller UserController

HERE,

  • The above command creates a controller named UserController in app/Http/Controllers directory

Update the controller code to the following

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(){
        return 'Congratulations. User account has successfully been created.';
    }

    public function create(){
        $params = [
            'title' => 'User Registration',
        ];

        return view('users.create')->with($params);
    }

    public function store(Request $request){
        $request->validate([
            'username' => 'required|alpha_dash',
            'email' => 'required|email',
            'password' => 'required'
        ]);

        return redirect()->route('users.index');
    }
}

HERE,

  • public function index(){...} defines the index method that outputs simple text in the web browser
  • public function create(){...} defines the create method that displays the user registration form.
  • public function store(Request $request){...} defines that store method that validates our user input then redirects to the users.index route. For simplicity's sake, we are not writing the values to the database.

Now that we have created our view and controller, let's wrap it up with the routes

Open /routes/web.php

Add the following routes

Route::get('/users',[
    'uses' => 'UserController@index',
    'as' => 'users.index'
]);

Route::get('/register',[
    'uses' => 'UserController@create',
    'as' => 'users.create'
]);

Route::post('/register',[
    'uses' => 'UserController@store',
]);

HERE,

  • we define three routes, users.index, and users.create. users.create has two HTTP verbs GET and POST that use the same path.

Let's now start our built-in web server to see how our application functions.

Run the following command

php artisan serve

Load the following route into your browser

http://127.0.0.1:8000/register

You should be able to see the following form

Laravel before validation

Click on Register button

You should be able to see the following errors

Laravel 6 Validation

Fill in the required details and click on Register

You should be able to see the following simple message if all validation rules pass

Congratulations. User account has successfully been created.

Try to enter valid data for the username then click on register to see what happens.

Summary

In this lesson, we covered the basics of Laravel form validation. We also created a simple practical example that shows us how to implement validation in Laravel and display errors to the user. We also learnt how to preserve the user input when validation passes for some fields and fails for others.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...