It is very important to filter incoming data in your web application. Laravel providers different ways to perform form validation in your laravel application.
Let's understand how practically form validation works in laravel. Let say we have a blog create page where we display:
- A form with title and body fields
Let's create two routes first open routes/web.php file and add following two lines:
Route::get('post', 'PostController@create'); Route::post('post', 'PostController@store');
Now, we need to create a new controller with save method. Open your terminal window and type following command to generate our controller:
php artisan make:controller PostController
Above method will generate a new PostController in app/Http/Controllers folder. Open the file and add following methods:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class PostController extends Controller { public function create() { return view('post'); } function store(Request $request) { $validator = Validator::make($request->all(), [ 'body' => 'required', 'title' => 'required|unique:posts|max:255', ]); if ($validator->fails()) { // redirect back to post create page // with submitted form data return redirect('post') ->withErrors($validator) ->withInput(); } // store your post data } }
Create function will render a view called post while store method will perform validation on our form data.
$validator = Validator::make($request->all(), [ 'body' => 'required', 'title' => 'required|unique:posts|max:255', ]);
Validator facade basically takes the request variables and next parameter will be array of fields that we want to validate. Consider following line:
'title' => 'required|unique:posts|max:255'
We want laravel to perform validation on title form field. All validation rules are seperated with pipe (|) symbol. Laravel runs validation in provided order and returns true if validation pass otherwise Validator object wiil have some errors.
Now, let's create our view file. Go to resources/views folder and create a new file called post.blade.php and add following contents:
<!DOCTYPE html> <html lang="en"> <head> <title>Laravel</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> .form-style-9{ max-width: 450px; background: #FAFAFA; padding: 30px; margin: 50px auto; box-shadow: 1px 1px 25px rgba(0, 0, 0, 0.35); border-radius: 10px; border: 6px solid #305A72; } .form-style-9 ul{ padding:0; margin:0; list-style:none; } .form-style-9 ul li{ display: block; margin-bottom: 10px; min-height: 35px; } .form-style-9 ul li .field-style{ box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; padding: 8px; outline: none; border: 1px solid #B0CFE0; -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; -o-transition: all 0.30s ease-in-out; }.form-style-9 ul li .field-style:focus{ box-shadow: 0 0 5px #B0CFE0; border:1px solid #B0CFE0; } .form-style-9 ul li .field-split{ width: 49%; } .form-style-9 ul li .field-full{ width: 100%; } .form-style-9 ul li input.align-left{ float:left; } .form-style-9 ul li input.align-right{ float:right; } .form-style-9 ul li textarea{ width: 100%; height: 100px; } .form-style-9 ul li input[type="button"], .form-style-9 ul li input[type="submit"] { -moz-box-shadow: inset 0px 1px 0px 0px #3985B1; -webkit-box-shadow: inset 0px 1px 0px 0px #3985B1; box-shadow: inset 0px 1px 0px 0px #3985B1; background-color: #216288; border: 1px solid #17445E; display: inline-block; cursor: pointer; color: #FFFFFF; padding: 8px 18px; text-decoration: none; font: 12px Arial, Helvetica, sans-serif; } .form-style-9 ul li input[type="button"]:hover, .form-style-9 ul li input[type="submit"]:hover { background: linear-gradient(to bottom, #2D77A2 5%, #337DA8 100%); background-color: #28739E; } form .alert ul { margin-bottom: 2em; } form .alert ul li { color: red; margin: 5px 0; min-height: auto; } </style> </head> <body> <form method="post" class="form-style-9"> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @csrf <ul> <li> <input type="text" name="title" class="field-style field-full align-none" placeholder="Post Title" value="{{ old("title") }}" /> </li> <li> <textarea name="body" class="field-style" placeholder="Post Body">{{ old("body") }}</textarea> </li> <li> <input type="submit" value="Save Post" /> </li> </ul> </form> </body> </html>
Let's have a look at the view code and see what we are doing here:
- We have html code with some style that we want to apply on our form
- We have added error block shown below to display form errors
@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
To generate csrf token we have added following code:
@csrf
Now, run following command to run your application:
php artisan serve
Now, open your web browser and hit http://localhost:8000/post. This page will display your post form. Try submitting form without any form values and see if you see form errors.
List of available validation rules
Following is a list of all available validation rules in laravel that you can use.
Rule | Example | Description |
---|---|---|
accepted | 'field' => 'accepted' | Useful for checkbox validation it must be yes, on, 1 or true |
active_url | 'field' => 'active_url' |
The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function
|
after:date | 'field' => 'date|after:tomorrow' | The field under validation must be a value after a given date |
after_or_equal:date | 'field' => 'date|after_or_equal:other_field' | The field under validation must be a value after or equal to the given date. |
alpha | 'field => 'required|alpha' | The field under validation must be entirely alphabetic characters. |
alpha_dash | 'field' => 'required|alpha_dash' | The field under validation may have alpha-numeric characters, as well as dashes and underscores. |
alpha_num | 'field' => 'required|alpha_num' | The field under validation must be entirely alpha-numeric characters. |
array | 'field' => 'array' |
The field under validation must be a PHP array .
|
bail | 'field' => 'bail|required' | Stop running validation rules after the first validation failure. |
before:date | 'field' => 'date|before:tomorrow' | The field under validation must be a value preceding the given date. |
before_or_equal:date | 'field' => 'date|before_or_equal:other_field' | The field under validation must be a value preceding or equal to the given date. |
between:min,max | 'field' => 'required|between:1,10' | The field under validation must have a size between the given min and max. |
boolean | 'field' => 'boolean' |
The field under validation must be able to be cast as a boolean. Allowed: true , false , 1 , 0 , "1" , and "0" .
|
confirmed | 'field' => 'confirmed' |
If the field under validation is password , a matching password_confirmation field must be present.
|
date | 'field' => 'date' |
The field under validation must be a valid, non-relative date according to the strtotime PHP function.
|
date_equals:date | 'field' => 'date|date_equals:compare_field' | The field under validation must be equal to the given date. |
date_format:format | 'field' => 'date|date_format:YYYY:mm:dd' | The field under validation must match the given format. |
different:field | 'field' => 'different:compare_field' | The field under validation must have a different value than field. |
digits:value | 'field' => 'digits:10' | The field under validation must be numeric and must have an exact length of value. |
digits_between:min,max | 'field' => 'digits_between:0,10' | The field under validation must have a length between the given min and max. |
dimensions | 'avatar' => 'dimensions:min_width=100,min_height=200' | The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters: Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio. |
distinct | 'foo.*.id' => 'distinct' | When working with arrays, the field under validation must not have any duplicate values. |
'field' => 'email' | The field under validation must be formatted as an e-mail address. | |
ends_with:word1,word2 | 'field' => 'ends_with:foo,bar' | The field under validation must end with one of the given values. |
exists:table,column | 'country' => 'exists:countries' | The field under validation must exist on a given database table. |
file | 'field' => 'file' | The field under validation must be a successfully uploaded file. |
filled | 'field' => 'filled' | The field under validation must not be empty when it is present. |
gt:field | 'field' => 'gt:100' | The field under validation must be greater than the given field. |
gte:field | 'field' => 'gte:100' | The field under validation must be greater than or equal to the given field. |
image | 'field' => 'image' | The file under validation must be an image (jpeg, png, bmp, gif, svg, or webp) |
in:foo,bar | 'field' => 'in:foo,bar' | The field under validation must be included in the given list of values. |
integer | 'field' => 'integer' | The field under validation must be an integer. |
ip | 'field' => 'ip' | The field under validation must be an IP address. |
json | 'field' => 'json' | The field under validation must be a valid JSON string. |
lt:field | 'field' => 'lt:100' | The field under validation must be less than the given field. |
lte:field | 'field' => 'lte:100' | The field under validation must be less than or equal to the given field. |
max:value | 'field' => 'max:100' | The field under validation must be less than or equal to a maximum value. |
mimetypes:text/plain | 'photo' => 'mimes:jpeg,bmp,png' | The file under validation must match one of the given MIME types |
min:value | 'field' => 'min:100' | The field under validation must have a minimum value. |
not_in:foo,bar | 'field' => 'not_in:foo,bar' | The field under validation must not be included in the given list of values. |
not_regex:pattern | 'email' => 'not_regex:/^.+$/i' | The field under validation must not match the given regular expression. |
nullable | 'field' => 'nullable' |
The field under validation may be null .
|
numeric | 'field' => 'numeric' | The field under validation must be numeric. |
present | 'field' => 'present' | The field under validation must be present in the input data but can be empty. |
regex:pattern | 'email' => 'regex:/^.+$/i' | The field under validation must match the given regular expression. |
required | 'field' => 'required' | The field under validation must be present in the input data and not empty. |
string | 'field' => 'string' | The field under validation must be a string. |
unique:table,column,except,id | 'email' => 'unique:users,email_address' | The field under validation must not exist within the given database table. |
url | 'field' => 'url' | The field under validation must be a valid URL. |
uuid | 'field' => 'uuid' | The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) UUID. |