RegisterLogin
DocsPricing
RegisterLogin
  • Getting Started
  • Introduction
  • Quick Start
  • SDKs
  • React
  • TypeScript
  • Next.js
  • Express
  • NestJS
  • Python
  • API Reference
  • Support and Resources
  • FAQ
  • Contact Support

AuthSafe

Product

HighlightFeatureIntegrationPricingFAQ

Company

AboutBlogContactSitemap

Developer

DashboardDocumentation

Legal

Terms & ConditionsPrivacyComplianceShippingCancellation

© 2026 AuthSafe. All rights reserved.

We value your privacy

This website uses cookies for anonymous analytics to help us improve your experience. No personal information is stored or shared. You can allow or reject analytics tracking at any time. See our Privacy Policy.

We use cookies for anonymous analytics. No personal info is stored. See our Privacy Policy.

Utilities

Helper functions for password validation and security.

calculatePasswordStrength

Analyze password strength and get improvement suggestions.
import { calculatePasswordStrength } from 'authsafe-ts';

const result = calculatePasswordStrength(password: string): PasswordStrength

Return Type

interface PasswordStrength {
  score: number; // 0-4
  strength: 'weak' | 'medium' | 'strong' | 'very-strong';
  feedback: string[];
  suggestions: string[];
}
Score Levels:
  • 0 - Too weak (unacceptable)
  • 1 - Weak (discouraged)
  • 2 - Medium (acceptable)
  • 3 - Strong (good)
  • 4 - Very strong (excellent)

Scoring Criteria

The function evaluates passwords based on:
  1. Length - Longer passwords score higher
    • < 8 characters: penalty
    • 8-12 characters: neutral
    • 12-16 characters: bonus
    • > 16 characters: strong bonus
  2. Character Diversity
    • Lowercase letters
    • Uppercase letters
    • Numbers
    • Special characters (!@#$%^&*()_+-=[]{}|;:,.<>?)
  3. Patterns (penalties)
    • Common passwords (123456, password, qwerty, etc.)
    • Sequential characters (abc, 123)
    • Repeated characters (aaa, 111)
    • Keyboard patterns (qwerty, asdf)
  4. Entropy - Randomness and unpredictability

Usage Examples

Basic Usage

import { calculatePasswordStrength } from 'authsafe-ts';

const password = 'MySecureP@ssw0rd!';
const result = calculatePasswordStrength(password);

console.log('Score:', result.score); // 4
console.log('Strength:', result.strength); // "very-strong"
console.log('Feedback:', result.feedback); // []
console.log('Suggestions:', result.suggestions); // []

Weak Password

const weak = calculatePasswordStrength('password123');

console.log(weak);
// {
//   score: 0,
//   strength: 'weak',
//   feedback: [
//     'This is a very common password.',
//     'Password is too short.'
//   ],
//   suggestions: [
//     'Add uppercase letters.',
//     'Add special characters.',
//     'Use at least 12 characters.',
//     'Avoid common words and patterns.'
//   ]
// }

Registration Form Integration

import { calculatePasswordStrength } from 'authsafe-ts';

function validatePassword(password: string): boolean {
  const result = calculatePasswordStrength(password);

  // Require at least "medium" strength
  if (result.score < 2) {
    alert(`Password is ${result.strength}. ${result.feedback.join(' ')}`);
    return false;
  }

  return true;
}

// Usage in form
document.getElementById('signup-form').addEventListener('submit', (e) => {
  e.preventDefault();

  const password = document.getElementById('password').value;

  if (validatePassword(password)) {
    // Proceed with signup
    submitForm();
  }
});

Real-time Password Meter

<!DOCTYPE html>
<html>
  <head>
    <style>
      .strength-meter {
        height: 5px;
        border-radius: 3px;
        margin-top: 5px;
        transition: all 0.3s;
      }
      .strength-weak {
        background: #dc3545;
        width: 25%;
      }
      .strength-medium {
        background: #ffc107;
        width: 50%;
      }
      .strength-strong {
        background: #28a745;
        width: 75%;
      }
      .strength-very-strong {
        background: #007bff;
        width: 100%;
      }

      .feedback {
        margin-top: 10px;
        font-size: 0.875rem;
      }
      .feedback-item {
        color: #dc3545;
        margin: 3px 0;
      }
      .suggestion-item {
        color: #6c757d;
        margin: 3px 0;
      }
    </style>
  </head>
  <body>
    <input type="password" id="password" placeholder="Enter password" />
    <div class="strength-meter" id="strength-meter"></div>
    <div class="feedback" id="feedback"></div>

    <script type="module">
      import { calculatePasswordStrength } from 'authsafe-ts';

      const passwordInput = document.getElementById('password');
      const strengthMeter = document.getElementById('strength-meter');
      const feedbackDiv = document.getElementById('feedback');

      passwordInput.addEventListener('input', (e) => {
        const password = e.target.value;

        if (!password) {
          strengthMeter.className = 'strength-meter';
          feedbackDiv.innerHTML = '';
          return;
        }

        const result = calculatePasswordStrength(password);

        // Update meter
        strengthMeter.className = `strength-meter strength-${result.strength}`;

        // Show feedback
        let html = `<strong>Strength: ${result.strength.toUpperCase()}</strong><br>`;

        if (result.feedback.length > 0) {
          html += '<div style="margin-top: 8px;">Issues:</div>';
          result.feedback.forEach((item) => {
            html += `<div class="feedback-item">• ${item}</div>`;
          });
        }

        if (result.suggestions.length > 0) {
          html += '<div style="margin-top: 8px;">Suggestions:</div>';
          result.suggestions.forEach((item) => {
            html += `<div class="suggestion-item">• ${item}</div>`;
          });
        }

        feedbackDiv.innerHTML = html;
      });
    </script>
  </body>
</html>

React Component

import React, { useState } from 'react';
import { calculatePasswordStrength, PasswordStrength } from 'authsafe-ts';

export function PasswordInput() {
  const [password, setPassword] = useState('');
  const [strength, setStrength] = useState<PasswordStrength | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setPassword(value);

    if (value) {
      setStrength(calculatePasswordStrength(value));
    } else {
      setStrength(null);
    }
  };

  const getColorClass = () => {
    if (!strength) return '';
    const colors = {
      'weak': 'text-red-600',
      'medium': 'text-yellow-600',
      'strong': 'text-green-600',
      'very-strong': 'text-blue-600',
    };
    return colors[strength.strength];
  };

  return (
    <div>
      <input
        type="password"
        value={password}
        onChange={handleChange}
        placeholder="Enter password"
        className="border rounded px-3 py-2 w-full"
      />

      {strength && (
        <div className="mt-2">
          <div className={`font-semibold ${getColorClass()}`}>
            Strength: {strength.strength.toUpperCase()} ({strength.score}/4)
          </div>

          {strength.feedback.length > 0 && (
            <div className="mt-2">
              <div className="text-sm font-semibold">Issues:</div>
              {strength.feedback.map((item, i) => (
                <div key={i} className="text-sm text-red-600">• {item}</div>
              ))}
            </div>
          )}

          {strength.suggestions.length > 0 && (
            <div className="mt-2">
              <div className="text-sm font-semibold">Suggestions:</div>
              {strength.suggestions.map((item, i) => (
                <div key={i} className="text-sm text-gray-600">• {item}</div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Common Password Patterns (Blocked)

The function detects and penalizes these patterns:
  • Common passwords: password, 123456, qwerty, abc123, etc.
  • Sequential: 12345, abcde, zyxw
  • Repeated: 1111, aaaa, 0000
  • Keyboard patterns: qwerty, asdfgh, zxcvbn
  • Simple substitutions: p@ssw0rd (still weak)

Best Practices

  1. Minimum score of 2 for production use
  2. Show real-time feedback to users
  3. Enforce strong passwords for sensitive operations
  4. Combine with server-side validation
  5. Block common passwords from your database

Related

  • UserApi - Password change API
  • Type Definitions - PasswordStrength type
  • TypeScript SDK Overview