JavaScriptmediumJavaScript

Password Validator

Validate password strength with configurable rules

01

The problem

Need to enforce password complexity requirements

02

The solution

JavaScript
function validatePassword(password, options = {}) {
  const defaults = {
    minLength: 8,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSpecialChars: true,
    specialChars: '!@#$%^&*()_+-=[]{}|;:,.<>?'
  };
  
  const config = { ...defaults, ...options };
  const errors = [];
  
  if (password.length < config.minLength) {
    errors.push(`Password must be at least ${config.minLength} characters long`);
  }
  
  if (config.requireUppercase && !/[A-Z]/.test(password)) {
    errors.push('Password must contain at least one uppercase letter');
  }
  
  if (config.requireLowercase && !/[a-z]/.test(password)) {
    errors.push('Password must contain at least one lowercase letter');
  }
  
  if (config.requireNumbers && !/\d/.test(password)) {
    errors.push('Password must contain at least one number');
  }
  
  if (config.requireSpecialChars) {
    const specialRegex = new RegExp(`[${config.specialChars.replace(/[.*+?^${}()|[]\]/g, '\$&')}]`);
    if (!specialRegex.test(password)) {
      errors.push(`Password must contain at least one special character (${config.specialChars})`);
    }
  }
  
  return {
    isValid: errors.length === 0,
    errors: errors,
    score: calculatePasswordScore(password)
  };
}

function calculatePasswordScore(password) {
  let score = 0;
  if (password.length >= 8) score += 1;
  if (password.length >= 12) score += 1;
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score += 1;
  if (/\d/.test(password)) score += 1;
  if (/[^a-zA-Z0-9]/.test(password)) score += 1;
  return Math.min(score, 5);
}

03

Parameters

passwordstring

Password to validate

optionsobject

Validation options

04

Put it to work

Example
const result1 = validatePassword('Weak123');
console.log(result1.isValid); // false
console.log(result1.errors); // ["Password must be at least 8 characters long", ...]

const result2 = validatePassword('StrongP@ssw0rd');
console.log(result2.isValid); // true
console.log(result2.score); // 5 (strongest)

// Custom validation rules
const customOptions = {
  minLength: 10,
  requireSpecialChars: false
};
const result3 = validatePassword('MyLongPassword123', customOptions);
console.log(result3.isValid); // true