Validating a password using JavaScript

Password validation is a critical security feature in web applications. JavaScript provides powerful tools to implement client-side password validation that checks for complexity requirements like length, character types, and special symbols. This helps ensure users create strong passwords that protect their accounts from unauthorized access.

Problem Statement

We need to create a JavaScript function that validates passwords based on these criteria:

  • Password length must be between 6 and 20 characters

  • Must contain at least one digit (0-9)

  • Must contain at least one lowercase letter (a-z)

  • Must contain at least one uppercase letter (A-Z)

  • Must contain at least one special character from: !@#$%^&*()-+.

For example, the password "Ex@mpl3!" should return true since it meets all requirements.

Method 1: Using Regular Expression

Regular expressions provide a concise way to validate passwords using lookahead assertions. Each assertion checks for a specific requirement without consuming characters.

Example

The regex pattern uses positive lookaheads to ensure all requirements are met:

  • (?=.*\d) - requires at least one digit

  • (?=.*[a-z]) - requires at least one lowercase letter

  • (?=.*[A-Z]) - requires at least one uppercase letter

  • (?=.*[!@#$%^&*()\-+.]) - requires at least one special character

  • .{6,20} - ensures length between 6 and 20 characters

function validatePassword(password) {
   const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-+.]).{6,20}$/;
   return regex.test(password);
}

console.log(validatePassword("Abcdef123!"));  // Valid password
console.log(validatePassword("abc123"));      // Missing uppercase and special char
console.log(validatePassword("PASSWORD123!")); // Missing lowercase
console.log(validatePassword("Pass1!"));      // Too short
true
false
false
false

Method 2: Iteration Approach

The iteration method manually checks each character, providing more control and readable logic. This approach is easier to understand and modify for different requirements.

Example

This method uses boolean flags to track each requirement and iterates through the password character by character:

function validatePassword(password) {
   if (password.length < 6 || password.length > 20) {
      return false;
   }

   let hasDigit = false;
   let hasLowercase = false;
   let hasUppercase = false;
   let hasSpecialChar = false;
   const specialChars = "!@#$%^&*()-+.";

   for (let i = 0; i < password.length; i++) {
      const char = password[i];

      if (/[0-9]/.test(char)) {
         hasDigit = true;
      } else if (/[a-z]/.test(char)) {
         hasLowercase = true;
      } else if (/[A-Z]/.test(char)) {
         hasUppercase = true;
      } else if (specialChars.includes(char)) {
         hasSpecialChar = true;
      }

      // Early return if all requirements are met
      if (hasDigit && hasLowercase && hasUppercase && hasSpecialChar) {
         return true;
      }
   }
   
   return hasDigit && hasLowercase && hasUppercase && hasSpecialChar;
}

console.log(validatePassword("Abcdef123!"));  // Valid password
console.log(validatePassword("abc123"));      // Invalid - missing requirements
console.log(validatePassword("Short1!"));     // Valid password
console.log(validatePassword("verylongpasswordthatexceedstwentycharacters1A!")); // Too long
true
false
true
false

Comparison

Method Performance Readability Flexibility
Regular Expression Faster Concise but complex Harder to modify
Iteration Slightly slower More readable Easy to customize

Enhanced Validation with Feedback

For better user experience, provide specific feedback about which requirements are missing:

function validatePasswordWithFeedback(password) {
   const errors = [];
   
   if (password.length < 6) {
      errors.push("Password must be at least 6 characters long");
   }
   if (password.length > 20) {
      errors.push("Password must not exceed 20 characters");
   }
   if (!/\d/.test(password)) {
      errors.push("Password must contain at least one digit");
   }
   if (!/[a-z]/.test(password)) {
      errors.push("Password must contain at least one lowercase letter");
   }
   if (!/[A-Z]/.test(password)) {
      errors.push("Password must contain at least one uppercase letter");
   }
   if (!/[!@#$%^&*()\-+.]/.test(password)) {
      errors.push("Password must contain at least one special character");
   }
   
   return {
      isValid: errors.length === 0,
      errors: errors
   };
}

const result = validatePasswordWithFeedback("weak");
console.log("Valid:", result.isValid);
console.log("Errors:", result.errors);
Valid: false
Errors: [ 'Password must be at least 6 characters long',
  'Password must contain at least one digit',
  'Password must contain at least one uppercase letter',
  'Password must contain at least one special character' ]

Conclusion

Both regular expressions and iteration methods effectively validate passwords in JavaScript. Regular expressions offer better performance and conciseness, while iteration provides better readability and flexibility for complex validation rules.

Updated on: 2026-03-15T23:19:00+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements