Password Validation with Regex in Laravel : Step-by-Step-Guide | Code Abe Academy

This tutorial will teach you how to add Password Validation with Regex in Laravel Projects. Let’s do it step by step.



    Go to your project file location, and type cmd in the address bar to open the location in the Command Prompt. Then create a new project using following command.

    Create a new project
    composer create-project laravel/laravel password-validation
  1. Create password-validation.blade.php file
  2. Add Bootstrap CDN
  3. Add Form Container
  4. password-validation.blade.php 
    <section class="min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
          <div class="container-fluid ">
            <div class="row justify-content-md-center">
                <div class="col-md-10 ">
                    <div class="card px-5 py-3 mt-3 shadow">
    <h1 class="text-info text-center mt-2 mb-4">Password Validation </h1>
                    </div>
                </div>
            </div>
        </div>
        </section>
    
  5. Add form with Validation
  6. password-validation.blade.php
    <form class="needs-validation" action="" method="POST" novalidate>
                      @csrf
                      <div class="mb-2">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" name="password" id="password" placeholder="Enter Your Password" required>
                        <div class="invalid-feedback">
                          Your password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one special character, and one number.
                        </div>
                        <ul id="password-criteria" class="mt-2">
                          <li id="uppercase" class="invalid">At least one uppercase letter (A-Z)</li>
                          <li id="lowercase" class="invalid">At least one lowercase letter (a-z)</li>
                          <li id="special" class="invalid">At least one special character (!@#$%^&* etc.)</li>
                          <li id="number" class="invalid">At least one number (0-9)</li>
                          <li id="length" class="invalid">At least 8 characters long</li>
                        </ul>
                      </div>
          
                      <div class="mt-4 mb-2">
                        <div class="d-grid">
                          <button class="btn btn-success float-right" type="submit">Submit</button>
                        </div>
                      </div>
                    </form>
  7. Add form validation script.
  8. password-validation.blade.php
    <script>
            const passwordInput = document.getElementById('password');
            const passwordCriteria = document.getElementById('password-criteria');
            const uppercase = document.getElementById('uppercase');
            const lowercase = document.getElementById('lowercase');
            const special = document.getElementById('special');
            const number = document.getElementById('number');
            const length = document.getElementById('length');
            
            passwordInput.addEventListener('focus', function() {
              passwordCriteria.style.display = 'block';
            });
    
            passwordInput.addEventListener('blur', function() {
              passwordCriteria.style.display = 'none';
            });
            
            passwordInput.addEventListener('input', function() {
              const value = passwordInput.value;
    
              if (/[A-Z]/.test(value)) {
                uppercase.classList.remove('invalid');
                uppercase.classList.add('valid');
              } else {
                uppercase.classList.remove('valid');
                uppercase.classList.add('invalid');
              }
              
              if (/[a-z]/.test(value)) {
                lowercase.classList.remove('invalid');
                lowercase.classList.add('valid');
              } else {
                lowercase.classList.remove('valid');
                lowercase.classList.add('invalid');
              }
    
              if (/[!@#$%^&*(),.?":{}|<>]/.test(value)) {
                special.classList.remove('invalid');
                special.classList.add('valid');
              } else {
                special.classList.remove('valid');
                special.classList.add('invalid');
              }
    
              if (/\d/.test(value)) {
                number.classList.remove('invalid');
                number.classList.add('valid');
              } else {
                number.classList.remove('valid');
                number.classList.add('invalid');
              }
    
              if (value.length >= 8) {
                length.classList.remove('invalid');
                length.classList.add('valid');
              } else {
                length.classList.remove('valid');
                length.classList.add('invalid');
              }
            });
    
            (function() {
                'use strict';
                var forms = document.querySelectorAll('.needs-validation');
                Array.prototype.slice.call(forms)
                    .forEach(function(form) {
                        form.addEventListener('submit', function(event) {
                            if (!form.checkValidity()) {
                                event.preventDefault();
                                event.stopPropagation();
                            }
                            form.classList.add('was-validated');
                        }, false);
                    });
            })();
          </script>
    
  9. Add CSS.
  10. password-validation.blade.php
    <style>
          .invalid {
            color: red;
          }
          .valid {
            color: green;
          }
          #password-criteria {
            display: none;
          }
        </style>
    
  11. Create a route.
  12. Web.php
    Route::get('/', function () {
        return view('password-validation');
    });
    
  13. Add Regex Password validation to form input.
  14. password-validation.blade.php
    pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}"
    
  15. Add database to .env file.
  16. .env
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=password_validation_db
    DB_USERNAME=root
    DB_PASSWORD=
    
  17. Craete Password Table and Model.
  18. php artisan make:model PasswordValidation -m
    
  19. Craete Password column to Table.
  20. password_validations Table
    $table->string('password');
    
  21. Create Model.
  22. PasswordValidation Model
    protected $table = 'password_validations';
        protected $primarykey = 'id';
        protected $fillable = ['password'];
    
  23. Migrate the Table.
  24. php artisan migrate
    
  25. Create Password Controller.
  26. php artisan make:controller PasswordController
    
  27. Add savePassword route.
  28. web.php
    use App\Http\Controllers\PasswordController;
    
    Route::post('/savePassword',[PasswordController::class,'savePassword'])->name('savePassword');
    
  29. Add savePassword function.
  30. PasswordController
          use App\Models\PasswordValidation;
    use Illuminate\Support\Facades\Validator;
          
          
          public function savePassword(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'password' => 'required|string',
            ]);
    
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            }
    
            $passwordValidation = new PasswordValidation([
                'password' => $request->input('password'),
            ]);
    
    
            $passwordValidation->save();
    
            return redirect()->back()->with('success', 'Password added successful.');
        }
    
  31. Add success message.
  32. password-validation.blade.php
    @if (Session::has('success'))
        <div class="alert alert-success" role="alert">
            {{ Session::get('success') }}
        </div>
        @endif
    


Break Down of the Regex Validation Pattern

  • "(?=.*\d)" - ensures there is at least one digit.
  • "(?=.*[a-z])" - ensures there is at least one lowercase letter.
  • "(?=.*[A-Z])" - ensures there is at least one uppercase letter.
  • "(?=.*[\W_])" - ensures there is at least one special character (non-alphanumeric, including underscore).
  • ".{8,}" - ensures the password is at least 8 characters long.

Post a Comment

Previous Post Next Post