Laravel Validation Rules

admin_img Posted By Bajarangi soft , Posted On 15-01-2021

Validating the data coming from the user’s end is very important as it can help the user in filling proper data and prevent them from submitting any improper or malicious request.

Validation Rules in Laravel

In Laravel, there are Validation Rules which are predefined rules, which when used in Laravel application. There is a list of rules that can be used to validate the data being submitted by the user.
Laravel Form with Validation Rules and Default Error Messages
Syntax 1: Basic validation rules

$request->validate([
  'password' => 'required|min:8|max:255',
]);
 Syntax 2: You can also specify the rules in the form of array as shown below
$request->validate([
  'password' => ['required', 'min:8', 'max:255'],
]);
Syntax 2: You can specify Multiple Validating Fields.
$request->validate([
  'password' => 'required|min:8|max:255',
],
[
  'name' => ['required', 'min:5', 'max:255'],
]);
Example:
Create a view file in ‘resources/views’ directory with the name ‘login.blade.php’ and write the below code in that file.
<!DOCTYPE html> 
<html> 

<head> 
    <title>GeeksforGeeks</title> 
    <style> 
        input { 
            font-size: 18px; 
            padding: 5px 8px; 
            margin: 10px; 
        } 
        
        .error { 
            color: red; 
            font-size: 18px; 
        } 
    </style> 
</head> 

<body> 
    <form method="post" action="/login"> 
        @csrf 
        <input type="text" name="username"
            placeholder="Enter Username"> 
        <br> 
        <input type="password" name="password"
            placeholder="Enter Password"> 
        <br> 
        <input type="submit" name="submit"
            value="Submit"> 
    </form> 
    <ul class="error"> 
        @foreach($errors->all() as $error) 
        <li>{{ $error }}</li> 
        @endforeach 
    </ul> 
</body> 

</html>
Here, we are looping through all the validation error messages in ‘$errors’ variable using ‘@foreach’ directive.

Create a controller in ‘app/Http/Controllers’ directory with the name ‘LoginController.php’. Use command ‘php artisan make:controller LoginController’ to create this controller. Write the below validation code to validate the data submitted by the form.
<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

class LoginController extends Controller { 
    public function getValidate() { 
        return view('login'); 
    } 

    public function postValidate(Request $request) { 
        $request->validate([ 
            'username' => 'required', 
            'password' => 'required|min:8|max:255', 
        ]); 
    } 
} 

Here, ‘required’ is to give user an error when the user leaves the field empty. And ‘min’ is for minimum characters and ‘max’ is for maximum characters that can be entered.

Write the below code in ‘web.php’ file in ‘routes’ directory.
Route::get('login', 'LoginController@getValidate');
Route::post('login', 'LoginController@postValidate');
Here, we have specified the ‘get’ method for displaying the view of our login page and ‘post’ method for the validating the input data submitted by the user through the HTML form.
We get the output as shown above when we click on the submit button in the form. It gives these two lines of error for the empty input field as we have set these two fields as required using the ‘required’ validation rule in ‘postValidate’ function in

STEP: 2

These are default error messages that the Laravel displays.

Laravel Form with Validation Rules and Custom Error Messages
Syntax

$validateData = $request->validate([
    ‘password’ => ‘required|min:8|max:255’
], [
    ‘password.required’ => ‘The password field is required.’,
    ‘password.min’ => ‘The password must have at list 8 characters.’,
    ‘password.max’ => ‘The password cannot exceed 255 characters.’,
]);
Example :
1.
Create a view file in ‘resources/views’ directory with the name ‘login.blade.php’ and write the below code in that file.
<!DOCTYPE html> 
<html> 

<head> 
    <title>GeeksforGeeks</title> 
    <style> 
        input { 
            font-size: 18px; 
            padding: 5px 8px; 
            margin: 10px; 
        } 
        
        .error { 
            color: red; 
            font-size: 18px; 
        } 
    </style> 
</head> 

<body> 
    <form method="post" action="/login"> 
        @csrf 
        <input type="text" name="username"
            placeholder="Enter Username"> 
        <br> 
        <input type="password" name="password"
            placeholder="Enter Password"> 
        <br> 
        <input type="submit" name="submit"
            value="Submit"> 
    </form> 
    <ul class="error"> 
        @foreach($errors->all() as $error) 
        <li>{{ $error }}</li> 
        @endforeach 
    </ul> 
</body> 

</html>
Here, we are looping through all the validation error messages in ‘$errors’ variable using ‘@foreach’ directive.

2.Create a controller in ‘app/Http/Controllers’ directory with the name ‘LoginController.php’. Use command ‘php artisan make:controller LoginController’ to create this controller. Write the below validation code to validate the data submitted by the form.
<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

class LoginController extends Controller { 
    public function getValidate() { 
        return view('login'); 
    } 

    public function postValidate(Request $request) { 
        $request->validate([ 
            'username' => 'required', 
            'password' => 'required|min:8|max:255', 
        ], [ 
            'username.required' => 'Username field cannot be empty.', 
            'password.required' => 'Password field cannot be empty.', 
            'password.min' => 
            'Password must contain at least 8 characters or more.', 
            'password.max' => 
                        'Password must not exceed 255 characters.', 
        ]); 
    } 
} 

In the first array, ‘required’ is to give the user an error when the user leaves the field empty. And ‘min’ is for minimum characters and ‘max’ is for maximum characters that can be entered.

In the second array, we have specified the error message that we want to get displayed when a validation rule is checked and is found as true. That means when the username field is left empty then the error message for ‘username.required’ will get displayed and is the same for all the other. Because of this, we have to specify the custom error message for all the validations rules which we have specified.
So as you can see in the above code, we have specified 4 validation rules and that’s why we have 4 error messages specified in the second array.
3.Write the below code in ‘web.php’ file in ‘routes’ directory

Route::get('login', 'LoginController@getValidate');
Route::post('login', 'LoginController@postValidate');
Here, we have specified the ‘get’ method for displaying the view of our login page and ‘post’ method for the validating the input data submitted by the user through the HTML form.

Related Post