Skip to main content

Overview

The password validator provides three powerful functions for password validation, strength assessment, and confirmation matching. It includes protection against common passwords and customizable security requirements.

Available Functions

  • isPassword() - Validate passwords against security requirements
  • getPasswordStrength() - Calculate password strength with crack time estimates
  • isPasswordMatch() - Verify password confirmation matching

Common Use Cases

  • User registration with password requirements
  • Password strength indicators
  • Password change flows
  • Security policy enforcement

isPassword()

Validates a password against configurable security requirements.

Function Signature

isPassword(password, options)

Parameters

password
string
required
The password to validate.
options
object
Configuration options for password validation.
options.minLength
number
default:"8"
Minimum password length in characters.
options.maxLength
number
default:"128"
Maximum password length in characters.
options.requireUppercase
boolean
default:"true"
Require at least one uppercase letter (A-Z).
options.requireLowercase
boolean
default:"true"
Require at least one lowercase letter (a-z).
options.requireNumbers
boolean
default:"true"
Require at least one number (0-9).
options.requireSymbols
boolean
default:"true"
Require at least one special character/symbol.
options.forbidCommonPasswords
boolean
default:"true"
Reject commonly used passwords (e.g., “password123”, “qwerty”).
options.details
boolean
default:"false"
Return detailed validation information instead of a boolean.

Return Value

result
boolean | object
When details is false: Returns true if valid, false otherwise.When details is true: Returns an object:
valid
boolean
Whether the password meets all requirements.
errors
string[] | null
Array of validation error messages, or null if valid.
password
string
The trimmed password that was validated.

Examples

import { isPassword } from 'validauth';

// Valid password (meets default requirements)
isPassword('SecureP@ss123');
// Returns: true

// Invalid - too short
isPassword('Pass1!');
// Returns: false

// Invalid - no symbols
isPassword('Password123');
// Returns: false

getPasswordStrength()

Calculates the strength of a password with estimated crack time.

Function Signature

getPasswordStrength(password, options)

Parameters

password
string
required
The password to evaluate.
options
object
options.details
boolean
default:"false"
Return detailed strength information.

Return Value

result
string | object
When details is false: Returns 'weak', 'medium', or 'strong'.When details is true: Returns an object:
strength
string
Password strength: 'weak', 'medium', or 'strong'.
score
number
Numerical score from 0-100.
estimatedCrackTimeInYears
number
Estimated time to crack in years.
crackTimeDisplay
string
Human-readable crack time (e.g., “1 billion years”).

Examples

import { getPasswordStrength } from 'validauth';

getPasswordStrength('password');
// Returns: 'weak'

getPasswordStrength('MyPassword123');
// Returns: 'medium'

getPasswordStrength('C0mpl3x!P@ssw0rd#2024');
// Returns: 'strong'

Strength Calculation

The strength score (0-100) is calculated based on:
Scoring Breakdown
  • Length (up to 40 points): +10 for each threshold (8, 12, 16, 20+ chars)
  • Character variety (up to 40 points): +10 each for lowercase, uppercase, numbers, symbols
  • Complexity bonus (up to 20 points): Extra points for long passwords with varied character types
  • Common password penalty: Score set to 0 if password is in common list
Strength Thresholds:
  • Weak (0-39): Less than 40 points
  • Medium (40-69): 40-69 points
  • Strong (70-100): 70+ points

isPasswordMatch()

Verifies that two passwords match (for password confirmation).

Function Signature

isPasswordMatch(password, confirmPassword, options)

Parameters

password
string
required
The original password.
confirmPassword
string
required
The confirmation password to compare.
options
object
options.details
boolean
default:"false"
Return detailed match information.

Return Value

result
boolean | object
When details is false: Returns true if passwords match, false otherwise.When details is true: Returns an object:
match
boolean
Whether the passwords match.
errors
string[] | null
Array of error messages, or null if matching.

Examples

import { isPasswordMatch } from 'validauth';

// Matching passwords
isPasswordMatch('SecureP@ss123', 'SecureP@ss123');
// Returns: true

// Non-matching passwords
isPasswordMatch('SecureP@ss123', 'SecureP@ss124');
// Returns: false

// With details
const result = isPasswordMatch('pass1', 'pass2', { details: true });
console.log(result);
/* Returns:
{
  match: false,
  errors: ['Passwords do not match']
}
*/

Complete Registration Example

import { isPassword, getPasswordStrength, isPasswordMatch } from 'validauth';

function validateRegistrationPassword(password, confirmPassword) {
  // Step 1: Validate password meets requirements
  const validation = isPassword(password, {
    minLength: 12,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSymbols: true,
    forbidCommonPasswords: true,
    details: true
  });

  if (!validation.valid) {
    return {
      success: false,
      message: 'Password does not meet requirements',
      errors: validation.errors
    };
  }

  // Step 2: Check password strength
  const strength = getPasswordStrength(password, { details: true });
  
  if (strength.strength === 'weak') {
    return {
      success: false,
      message: 'Password is too weak',
      strength: strength
    };
  }

  // Step 3: Verify password match
  const match = isPasswordMatch(password, confirmPassword, { details: true });
  
  if (!match.match) {
    return {
      success: false,
      message: 'Passwords do not match',
      errors: match.errors
    };
  }

  return {
    success: true,
    message: 'Password is valid and strong',
    strength: strength
  };
}

// Usage
const result = validateRegistrationPassword(
  'MySecure!Pass123',
  'MySecure!Pass123'
);

if (result.success) {
  console.log('Password accepted:', result.strength);
} else {
  console.error('Password rejected:', result.message);
}

Password Strength Indicator

import { getPasswordStrength } from 'validauth';

function displayPasswordStrength(password) {
  const result = getPasswordStrength(password, { details: true });
  
  const colors = {
    weak: '#ff4444',
    medium: '#ffaa00',
    strong: '#00cc66'
  };
  
  const strengthBar = {
    strength: result.strength,
    color: colors[result.strength],
    percentage: result.score,
    message: `${result.strength.toUpperCase()} - Would take ${result.crackTimeDisplay} to crack`
  };
  
  return strengthBar;
}

// Usage in UI
const indicator = displayPasswordStrength('MyP@ssw0rd123');
console.log(indicator);
/* Returns:
{
  strength: 'medium',
  color: '#ffaa00',
  percentage: 50,
  message: 'MEDIUM - Would take 100000 years to crack'
}
*/

Validation Rules

Accepted Symbol Characters

The following symbols are considered valid special characters:
! @ # $ % ^ & * ( ) _ + - = [ ] { } ; ' : " \ | , . < > / ?

Common Password Protection

The validator includes a list of common passwords that are automatically rejected when forbidCommonPasswords is enabled. This includes passwords like “password”, “123456”, “qwerty”, and thousands of other commonly used passwords.

Best Practices

Security Recommendations
  • Set minLength to at least 12 characters for better security
  • Always enable forbidCommonPasswords in production
  • Use getPasswordStrength() to guide users toward stronger passwords
  • Implement rate limiting on password validation endpoints
  • Never store passwords in plain text - always use proper hashing

Progressive Password Requirements

import { isPassword, getPasswordStrength } from 'validauth';

function getPasswordRequirements(accountType) {
  const requirements = {
    basic: {
      minLength: 8,
      requireUppercase: false,
      requireSymbols: false
    },
    standard: {
      minLength: 10,
      requireUppercase: true,
      requireSymbols: true
    },
    premium: {
      minLength: 12,
      requireUppercase: true,
      requireSymbols: true,
      // Additional check for strong passwords
      validateStrength: true
    }
  };
  
  return requirements[accountType] || requirements.standard;
}

function validateByAccountType(password, accountType) {
  const req = getPasswordRequirements(accountType);
  const isValid = isPassword(password, req);
  
  if (req.validateStrength && isValid) {
    const strength = getPasswordStrength(password);
    return strength === 'strong';
  }
  
  return isValid;
}

Error Handling

import { isPassword } from 'validauth';

function handlePasswordValidation(password) {
  try {
    const result = isPassword(password, { details: true });
    
    if (!result.valid) {
      // Return user-friendly error messages
      return {
        success: false,
        errors: result.errors.map(error => ({
          field: 'password',
          message: error
        }))
      };
    }
    
    return { success: true };
  } catch (error) {
    console.error('Unexpected validation error:', error);
    return {
      success: false,
      errors: [{ field: 'password', message: 'Validation failed' }]
    };
  }
}

Build docs developers (and LLMs) love