Understanding Laravel Validation Rules Example Tutorial

Understanding Laravel Validation Rules Example

This Laravel tutorial is going to focus on How to validate HTML forms using Laravel Validation mechanism in Laravel applications? 

After designing the front-end layout of the application, and business logic, the next step is to validate the user input data in Laravel applications.

 

If you are a beginner to Laravel MVC, then we recommend to study the following topics:

 

Laravel Validation – Introduction

Laravel Validation is one of the most important parts of Laravel Application Development. The Validation process makes sure that no garbage and unexpected user data is sent to the server and database.

So, we validate the Mobile numbers, email addresses, IP addresses and even much more depending upon the application logic and rules.

Laravel provides multiple ways to validate the incoming HTTP request data with a predefined set of validation rules.

We will discuss them all in a later section of the post…

Read our detailed chapter Laravel Request Lifecycle, How Laravel request received and served.

How Laravel Validation Works?

Laravel framework provides developers with different methods to validate the incoming user data at the server side. By default, Laravel uses a validate() method of Illuminate\Http\Request object which validates incoming HTTP request with a set of powerful Laravel validation rules.

If the defined validation rules pass, the application will continue execution. However, if validation fails, the Laravel framework throws an exception and proper error message will automatically be sent back to the user. Then, the user can present an appropriate error message to views.

Note: For AJAX requests, Laravel sent back an error in the form of JSON message. While in normal requests, an HTTP response will be sent back to the client application.

There are following basic steps Larevel use to validate the user input data:

  1. Create HTML forms in the Laravel Views
  2. Define Validation rules in the controller
  3. Display the validation errors in HTML Views

 

Also, read Advanced Laravel concepts:

 

Simple Method – Laravel Validation in Controller

Laravel provides multiple ways to validate the incoming user requests. Using the validate() method is one of the simple methods. Let’s start with the simpler method using validate():

Validate using validate() method in the Controller

Remember that all the Laravel controllers use the “ValidatesRequests” trait, which provides
a convenient validate() method to validate user input data. Following are simple steps:

Laravel Validation Example

Step1 – Define routes
// routes/web.php
Route::get(‘blogs/create’, ‘BlogsController@create’);
Route::post(‘blogs/save’, ‘BlogsController@store’);

Step2 – Define Controller functions:
// app/Http/Controllers/BlogsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BlogsController extends Controller
{
public function create()
{
   return view(‘blogs.create’);
}
public function store(Request $request)
{   
    $this->validate($request, [
    ‘title’ => ‘required|unique:blogs|max:125’,
    ‘body’ => ‘required’
]);
// Blog is valid; proceed to save it
}
}

The above two line of validation code is doing great stuff for us.

Let’s understand what happens under the hood.

1. First of all, in the controller function, we have defined the fields we expect and applying rules.

    More than one field is separated by the pipe character, | to each individually.

2. Next, the validate() method checks the incoming HTTP request data containing in the $request.

3. If user data is valid, the validate() method stops and execute the best part of the controller logic.

4. But, if any of the validation rules fail, validate() throws an exception of type ValidationException.

5. If the request is Ajax – the exception will create a JSON response containing the validation errors. If normal HTTP request, the exception will return a redirect to the previous page, together with all of the user input and the validation errors—perfect for repopulating a failed form and showing some errors

Note – Here, ‘required’, ‘unique’ is the validation rules. We will learn all available Laravel validation rules.

Display Validation Errors Messages in Views Laravel

Whenever the validation fails, Laravel automatically redirects the user back to the previous page. The validate() method in controllers (and the withErrors() method on redirects that it relies on) flashes any errors to the session. These errors are made available to the view you’re being redirected to in the $errors variable.

The $errors variable will be an instance of Illuminate\Support\MessageBag.

So, in our example, the user will be redirected to our controller’s create method when validation fails, allowing us to display the error messages in the view:

<!– /resources/views/blogs/create.blade.php –>

<h1>New Blog</h1>

@if ($errors->any())
<div class=”alert alert-danger”>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<!– New Blog Form –>

Here, $errors is an array of validation failed messages.

Laravel Manual Validation – Creating Validators in Laravel

If you are not working in a controller, or if don’t want to use validate() method on the request. You can manually create a Validator instance and check for success or failure using the Validator facade.

In this case, The make() method on the facade generates a new validator instance.

Laravel manual validation example
Route::post(‘blog’, function (Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
‘title’ => ‘required|unique:recipes|max:125’,
‘body’ => ‘required’
]);
if ($validator->fails()) {
return redirect(‘recipes/create’)
->withErrors($validator)
->withInput();
}
// Blog is valid; proceed to save it
});

Here, the first parameter to Validator is request data ($request->all) and second parameter is validation rules using which te data would be validated. The validator exposes a fails() method that we can check against and can be passed into the withErrors() method of the redirect.

Understanding Laravel withErrors(), withError(), withSuccess(), and withInput() methods:

As we know that upon validation failure, Laravel flash an error data into the session.

The withError() will add flash data under the key error, withErrors() will add flash data under the key errors, and withSuccess() will add flash data under the key of success; and so on The withErrors method accepts a validator, a MessageBag, or a PHP array.

How to Stop Laravel Validation on First Failure

By default, in case of multiple validation rules, Laravel perform all the specified validation checks.
But, sometimes we may want to stop validation on the first failure and return back to the user.

To achieve this, a special validation rule “bail” is assigned to the attribute.

$request->validate([
‘title’ => ‘bail|required|unique:posts|max:255’,
‘body’ => ‘required’,
]);

Validation Rules are validated in the order they are assigned. Here, if the first rule “required” fails, the validation will stop and would not validate next rule max, etc.

List of Laravel Validation Rules

Laravel provides a great set of default validation rules to validate all the incoming user input data.

Laravel Validation rule syntax:
‘fieldname1’ => ‘rule1|rule2|rule3’,
‘fieldname21’ => ‘rule1|rule2|rule3’

1. Require the field
required; required_if:anotherField,equalToThisValue;
required_unless:anotherField,equalToThisValue

2. Field must contain certain types of character
alpha, alpha_dash, alpha_num, numeric, integer

3. Field must contain certain patterns
email, active_url, ip

4. Dates
after:date, before:date (date can be any valid string that strtotime() can
handle)

5. Numbers
between:min,max, min:num, max:num, size:num (size tests against length for
strings, value for integers, count for arrays, or size in KB for files)

6. Databases
exists:tableName, unique:tableName (expects to look in the same table column
as the field name; see the docs for how to customize)

7. Image dimensions
dimensions:min_width=XXX; can also use and/or combine with max_width,
min_height, max_height, width, height, and ratio

8. bail – Stop running validation rules after the first validation failure.

9. date – the specified value must be a valid date.

10. email – The field under validation must be formatted as an e-mail address. This is How to validate email address in Laravel

11. file – The field under validation must be a successfully uploaded file.

12. image – The file under validation must be an image (jpeg, png, bmp, gif, or svg)

13. ip – The field under validation must be an IP address whether its ipv4 or ipv6 address.

14. ipv4 – The field under validation must be an IPv4 address. This is How to validate ipv4 address in Laravel

15. ipv6 – The field under validation must be an IPv6 address. This is How to validate ipv6 address in Laravel

16. max:value – The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

17. required – The field under validation must be present in the input data and not empty

18 url – The field under validation must be a valid URL.

Final Words

Today, we have learned the basics of Laravel Validation mechanism and simple steps to validate the incoming HTTP request data. The Validation process makes the application robust and error-free. Then, we discussed inbuilt Laravel validation rules to perform different types of checks on user input data.

Further Reading:

Laravel official documentation

Laravel 5 Validation

Leave a Reply

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