Strong Password Validation in JavaScript

Strong Password Validation in JavaScript
Project: Vanilla Javascript Password Validation
Author: Daria
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet provides real-time validation for a password input field to check if it is weak or strong. It checks various criteria to ensure password strength. The code listens for a keyup event on the password field and performs the following checks for a strong password:

  • Minimum character length of 8
  • Presence of at least one lowercase letter
  • Presence of at least one uppercase letter
  • Presence of at least one special character or number

Each requirement is visually indicated using CSS classes on corresponding helper text elements. If all requirements are met, the password field’s parent element is marked as valid. Otherwise, the parent element is marked as invalid.

The code utilizes helper functions to add or remove CSS classes and check for the presence of a class on an element. By implementing this code, users can receive immediate feedback on the strength and validity of their chosen password.

How to Create Strong Password Validation in Javascript

Create the HTML form element with an input for the password field as follows:

<form>
    <label for="password">Password</label>
      <!-- change type to text to see the password  -->
    <input class="password" name="password" type="password" />

    <ul class="helper-text">
        <li class="length">Must be at least 8 characters long.</li>
        <li class="lowercase">Must contain a lowercase letter.</li>
        <li class="uppercase">Must contain an uppercase letter.</li>
        <li class="special">Must contain a number or special character.</li>
    </ul>
</form>

Style the password field using the following CSS styles. These CSS rules are optional, you can define your own CSS according to your needs.

html, body {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  background: green;
  color: #454545;
}
body * {
  box-sizing: border-box;
}
body *:focus {
  outline: 0;
}

form {
  width: 320px;
  height: 224px;
  padding: 35px;
  background: #ffffff;
}
form label {
  display: block;
  font-weight: bold;
  margin-bottom: 6px;
}
form input[type=text],
form input[type=password] {
  display: block;
  height: 36px;
  margin-bottom: 8px;
  padding: 0 36px 0 10px;
  border: 2px solid green;
  font-size: 16px;
  letter-spacing: 1px;
}
form ul.helper-text {
  display: block;
  margin-top: 6px;
  font-size: 12px;
  line-height: 22px;
  color: red;
}
form ul.helper-text li.valid {
  color: blue;
}
form.valid input {
  border: 2px solid blue;
}

Finally, use the following JavaScript function to validate the password:

(function(){
    var password = document.querySelector('.password');
    
    var helperText = {
        charLength: document.querySelector('.helper-text .length'),
        lowercase: document.querySelector('.helper-text .lowercase'),
        uppercase: document.querySelector('.helper-text .uppercase'),
        special: document.querySelector('.helper-text .special')
    };
    
    var pattern = {
        charLength: function() {
            if( password.value.length >= 8 ) {
                return true;
            }
        },
        lowercase: function() {
            var regex = /^(?=.*[a-z]).+$/; // Lowercase character pattern

            if( regex.test(password.value) ) {
                return true;
            }
        },
        uppercase: function() {
            var regex = /^(?=.*[A-Z]).+$/; // Uppercase character pattern

            if( regex.test(password.value) ) {
                return true;
            }
        },
        special: function() {
            var regex = /^(?=.*[0-9_\W]).+$/; // Special character or number pattern

            if( regex.test(password.value) ) {
                return true;
            }
        }   
    };
    
    // Listen for keyup action on password field
  password.addEventListener('keyup', function (){
        // Check that password is a minimum of 8 characters
        patternTest( pattern.charLength(), helperText.charLength );
        
        // Check that password contains a lowercase letter      
        patternTest( pattern.lowercase(), helperText.lowercase );
        
        // Check that password contains an uppercase letter
        patternTest( pattern.uppercase(), helperText.uppercase );
        
        // Check that password contains a number or special character
        patternTest( pattern.special(), helperText.special );
    
    // Check that all requirements are fulfilled
    if( hasClass(helperText.charLength, 'valid') &&
              hasClass(helperText.lowercase, 'valid') && 
                hasClass(helperText.uppercase, 'valid') && 
              hasClass(helperText.special, 'valid')
        ) {
            addClass(password.parentElement, 'valid');
    }
    else {
      removeClass(password.parentElement, 'valid');
    }
    });
    
    function patternTest(pattern, response) {
        if(pattern) {
      addClass(response, 'valid');
    }
    else {
      removeClass(response, 'valid');
    }
    }
    
    function addClass(el, className) {
        if (el.classList) {
            el.classList.add(className);
        }
        else {
            el.className += ' ' + className;
        }
    }
    
    function removeClass(el, className) {
        if (el.classList)
                el.classList.remove(className);
            else
                el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
    
    function hasClass(el, className) {
        if (el.classList) {
            return el.classList.contains(className);    
        }
        else {
            new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className); 
        }
    }
    
})();

That’s all! hopefully, you have successfully integrated this JavaScript strong password validation code into your project. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply