UNPKG

test-pwd-strength

Version:

[![npm version](https://img.shields.io/npm/v/password-strength-checker.svg)](https://www.npmjs.com/package/password-strength-checker) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

64 lines (55 loc) 1.68 kB
/** * Check password strength based on customizable rules. * @param {string} password - The password to check. * @param {object} options - Configuration options. * @returns {object} - Strength result (score, feedback, etc.). */ function checkStrength(password, options = {}) { const defaults = { minLength: 8, requireUppercase: true, requireNumbers: true, requireSymbols: true, }; const config = { ...defaults, ...options }; const feedback = []; let score = 0; // Length check (max 30 points) const lengthPoints = Math.min(30, Math.floor(password.length / 8 * 30)); score += lengthPoints; if (password.length < config.minLength) { feedback.push(`Password must be at least ${config.minLength} characters.`); } // Character type checks (only if required) if (config.requireUppercase) { if (/[A-Z]/.test(password)) { score += 20; } else { feedback.push('Add at least one uppercase letter.'); } } if (config.requireNumbers) { if (/[0-9]/.test(password)) { score += 20; } else { feedback.push('Add at least one number.'); } } if (config.requireSymbols) { if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) { score += 30; } else { feedback.push('Add at least one symbol.'); } } if (!feedback.length) { feedback.push('The password looks perfect.'); } // Strength thresholds let strength; if (score >= 80) strength = 'strong'; else if (score >= 50) strength = 'medium'; else strength = 'weak'; return { score, strength, feedback }; } module.exports = { checkStrength };