Laravel | Validation Rules

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.

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 3: You can specify Multiple Validating Fields.

    $request->validate([
      'password' => 'required|min:8|max:255',
    ],
    [
      'name' => ['required', 'min:5', 'max:255'],
    ]);
    
  • Example:

    1. Create a view file in ‘resources/views’ directory with the name ‘login.blade.php’ and write the below code in that file.

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      <!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>

      chevron_right

      
      

      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.

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      <?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',
              ]);
          }
      }

      chevron_right

      
      

      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.

    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.

  • Output:

    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.

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      <!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>

      chevron_right

      
      

      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.

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      <?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.',
              ]);
          }
      }

      chevron_right

      
      

      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.

  • Output:

    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 custom error messages that we have set in step 2 in ‘postValidate’.

Reference: https://laravel.com/docs/6.x/validation




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.