Skip to main content

Introduction

ValidAuth provides a comprehensive set of functions for authentication validation and token generation in JavaScript applications. All functions are exported from the main package and can be imported individually or together.
import { isEmail, isPassword, generateOTP } from 'validauth';

API Organization

The ValidAuth API is organized into three main categories:

Validators

Functions that validate user input and credentials

Generators

Functions that generate secure tokens and passwords

Utilities

Helper functions for password strength and matching

Validators

Validation functions help ensure user input meets security requirements.

isEmail

Validates email addresses with customizable options

isPassword

Validates passwords against security requirements

isUsername

Validates usernames with configurable rules

validateOTP

Validates one-time password codes

isSessionTokenValid

Checks if session tokens are valid and not expired

isXSSSafe

Checks input for XSS attack patterns

Validator Functions

isEmail(email, options)

Validates an email address with extensive customization options. Parameters:
  • email (string): The email address to validate
  • options (Object, optional):
    • allowPlusAddressing (boolean): Allow plus addressing (default: true)
    • requireTLD (boolean): Require top-level domain (default: true)
    • blockedDomains (string[]): List of blocked domains (default: [])
    • details (boolean): Return detailed validation results (default: false)
Returns: boolean or Object (if details: true) Example:
isEmail('[email protected]'); // true
isEmail('[email protected]', { details: true });
// { valid: true, errors: null, email: '[email protected]', localPart: 'user', domain: 'example.com' }

isPassword(password, options)

Validates a password against security requirements. Parameters:
  • password (string): The password to validate
  • options (Object, optional):
    • minLength (number): Minimum length (default: 8)
    • maxLength (number): Maximum length (default: 128)
    • requireUppercase (boolean): Require uppercase letters (default: true)
    • requireLowercase (boolean): Require lowercase letters (default: true)
    • requireNumbers (boolean): Require numbers (default: true)
    • requireSymbols (boolean): Require symbols (default: true)
    • forbidCommonPasswords (boolean): Block common passwords (default: true)
    • details (boolean): Return detailed validation results (default: false)
Returns: boolean or Object (if details: true) Example:
isPassword('MyP@ssw0rd'); // true
isPassword('weak', { details: true });
// { valid: false, errors: ['Password must be at least 8 characters long', ...], password: 'weak' }

isUsername(username, options)

Validates a username with configurable rules. Parameters:
  • username (string): The username to validate
  • options (Object, optional):
    • minLength (number): Minimum length (default: 3)
    • maxLength (number): Maximum length (default: 30)
    • allowSpecialChars (boolean): Allow special characters (default: false)
    • forbidSpaces (boolean): Forbid spaces (default: true)
    • forbidStartingNumber (boolean): Forbid starting with number (default: true)
    • blockedUsernames (string[]): List of blocked usernames (default: [])
    • details (boolean): Return detailed validation results (default: false)
Returns: boolean or Object (if details: true) Example:
isUsername('john_doe'); // true
isUsername('admin', { blockedUsernames: ['admin', 'root'] }); // false

validateOTP(otp, correctOTP, options)

Validates an OTP code with attempt tracking. Parameters:
  • otp (string): The OTP code to validate
  • correctOTP (string): The correct OTP code to compare against
  • options (Object, optional):
    • attempts (number): Current attempt number
    • maxAttempts (number): Maximum attempts allowed (default: 3)
    • details (boolean): Return detailed validation results (default: false)
Returns: boolean or Object (if details: true) Example:
validateOTP('1234', '1234'); // true
validateOTP('0000', '1234', { attempts: 2, maxAttempts: 3, details: true });
// { valid: false, errors: ['Invalid OTP.'], otp: '0000', correctOTP: '1234', attempts: 2, remainingAttempts: 1, maxAttempts: 3 }

isSessionTokenValid(token, options)

Validates a session token to check if it’s still valid and not expired. Parameters:
  • token (string): The session token to validate
  • options (Object, optional):
    • length (number): Length of the random part (default: 32)
    • userID (string): User ID in the token (default: null)
    • expiresIn (string): Expiration time format (default: '1h')
    • includeTimestamp (boolean): Whether token has timestamp (default: true)
    • details (boolean): Return detailed validation results (default: false)
Returns: boolean or Object (if details: true) Example:
isSessionTokenValid(token, { expiresIn: '1h' }); // true or false
isSessionTokenValid(token, { expiresIn: '30m', details: true });
// { valid: true, errors: null, token: '...', timestamp: 1234567890, expiresAt: 1234569690, remainingTime: 1800000 }

isXSSSafe(input, options)

Checks if a string is safe from XSS (Cross-Site Scripting) attacks. Parameters:
  • input (string): The string to check for XSS patterns
  • options (Object, optional):
    • details (boolean): Return detailed validation results (default: false)
Returns: boolean or Object (if details: true) Example:
isXSSSafe('Hello World'); // true
isXSSSafe('<script>alert("xss")</script>'); // false
isXSSSafe('<script>alert("xss")</script>', { details: true });
// { safe: false, errors: ['Potential XSS detected: <script[^>]*>[s\S]*?</script>'], input: '<script>alert("xss")</script>' }

Generators

Generator functions create secure passwords, tokens, and OTP codes.

generatePassword

Generate strong, secure passwords

generateOTP

Generate one-time password codes

generateSessionToken

Generate secure session tokens

Generator Functions

generatePassword(options)

Generates a strong password based on specified criteria. Parameters:
  • options (Object, optional):
    • length (number): Password length (default: 12)
    • includeUppercase (boolean): Include uppercase letters (default: true)
    • includeLowercase (boolean): Include lowercase letters (default: true)
    • includeNumbers (boolean): Include numbers (default: true)
    • includeSymbols (boolean): Include symbols (default: true)
    • details (boolean): Return detailed information (default: false)
Returns: string or Object (if details: true) Example:
generatePassword(); // 'aB3#xY9@mK1!'
generatePassword({ length: 16, includeSymbols: false });
generatePassword({ details: true });
// { password: 'aB3#xY9@mK1!', length: 12, errors: [], strength: { strength: 'strong', score: 80, ... } }

generateOTP(options)

Generates an OTP code. Parameters:
  • options (Object, optional):
    • length (number): OTP code length (default: 4)
    • type (string): Type of OTP - 'numeric' or 'alphanumeric' (default: 'numeric')
    • details (boolean): Return detailed information (default: false)
Returns: string or Object (if details: true) Example:
generateOTP(); // '1234'
generateOTP({ length: 6, type: 'alphanumeric' }); // 'aB3x9Z'
generateOTP({ details: true });
// { code: '1234', length: 4, type: 'numeric' }

generateSessionToken(options)

Generates a secure session token with optional timestamp and user ID. Parameters:
  • options (Object, optional):
    • length (number): Token length (excluding timestamp/userID) (default: 32)
    • userID (string): User ID to include in token (default: null)
    • expiresIn (string): Expiration time (default: '1h')
    • includeTimestamp (boolean): Include timestamp (default: true)
    • details (boolean): Return detailed information (default: false)
Returns: string or Object (if details: true) Example:
generateSessionToken(); // 'aBcD...xyz1234567890'
generateSessionToken({ length: 64, userID: 'user123', expiresIn: '24h' });
generateSessionToken({ details: true });
// { token: 'aBcD...', userID: null, expiresIn: '1h', length: 45, timestamp: 1234567890, errors: null }

Utilities

Utility functions provide additional authentication-related functionality.

getPasswordStrength(password, options)

Calculates the strength of a password. Parameters:
  • password (string): The password to evaluate
  • options (Object, optional):
    • details (boolean): Return detailed strength analysis (default: false)
Returns: string or Object (if details: true) Returns one of: 'weak', 'medium', or 'strong' Example:
getPasswordStrength('MyP@ssw0rd123'); // 'strong'
getPasswordStrength('password'); // 'weak'
getPasswordStrength('MyP@ssw0rd123', { details: true });
// { strength: 'strong', score: 80, estimatedCrackTimeInYears: 31536000000, crackTimeDisplay: '31536000000 years' }

isPasswordMatch(password, confirmPassword, options)

Checks if two passwords match. Parameters:
  • password (string): The password
  • confirmPassword (string): The confirmation password
  • options (Object, optional):
    • details (boolean): Return detailed match results (default: false)
Returns: boolean or Object (if details: true) Example:
isPasswordMatch('MyP@ssw0rd', 'MyP@ssw0rd'); // true
isPasswordMatch('password1', 'password2'); // false
isPasswordMatch('password1', 'password2', { details: true });
// { match: false, errors: ['Passwords do not match'] }

Quick Reference Table

FunctionCategoryPurposeReturns
isEmailValidatorValidate email addressesboolean or Object
isPasswordValidatorValidate password strengthboolean or Object
isUsernameValidatorValidate username formatboolean or Object
validateOTPValidatorValidate OTP codesboolean or Object
isSessionTokenValidValidatorValidate session tokensboolean or Object
isXSSSafeValidatorCheck for XSS patternsboolean or Object
generatePasswordGeneratorGenerate secure passwordsstring or Object
generateOTPGeneratorGenerate OTP codesstring or Object
generateSessionTokenGeneratorGenerate session tokensstring or Object
getPasswordStrengthUtilityCalculate password strengthstring or Object
isPasswordMatchUtilityCompare two passwordsboolean or Object

Common Patterns

Detailed Responses

All validators and generators support a details option that returns comprehensive information:
// Simple boolean response
isEmail('[email protected]'); // true

// Detailed object response
isEmail('[email protected]', { details: true });
// {
//   valid: true,
//   errors: null,
//   email: '[email protected]',
//   localPart: 'user',
//   domain: 'example.com'
// }

Error Handling

When validation fails with details: true, the response includes an errors array:
isPassword('weak', { details: true });
// {
//   valid: false,
//   errors: [
//     'Password must be at least 8 characters long',
//     'Password must contain at least one uppercase letter',
//     'Password must contain at least one symbol'
//   ],
//   password: 'weak'
// }

TypeScript Support

ValidAuth is written in JavaScript but provides TypeScript type definitions for all functions. Import types alongside functions:
import { isEmail, type EmailOptions } from 'validauth';

const options: EmailOptions = {
  allowPlusAddressing: false,
  requireTLD: true,
  details: true
};

const result = isEmail('[email protected]', options);

Next Steps

Validators

Explore detailed validator documentation

Generators

Learn about token and password generation

Examples

See real-world usage examples

Best Practices

Learn best practices and configuration

Build docs developers (and LLMs) love