Skip to main content
This guide provides comprehensive, production-ready examples of using ValidAuth validators in common authentication scenarios.

Registration Form Validation

A complete user registration form with email, password, and username validation.
import { isEmail, isPassword, isUsername } from 'validauth';

function validateRegistration(formData) {
  const { email, password, username } = formData;
  const errors = {};
  
  // Validate email with strict rules
  const emailResult = isEmail(email, {
    allowPlusAddressing: false,
    requireTLD: true,
    blockedDomains: ['tempmail.com', 'throwaway.email', '10minutemail.com'],
    details: true
  });
  
  if (!emailResult.valid) {
    errors.email = emailResult.errors;
  }
  
  // Validate password with strong requirements
  const passwordResult = isPassword(password, {
    minLength: 10,
    maxLength: 128,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSymbols: true,
    forbidCommonPasswords: true,
    details: true
  });
  
  if (!passwordResult.valid) {
    errors.password = passwordResult.errors;
  }
  
  // Validate username with reserved names blocked
  const usernameResult = isUsername(username, {
    minLength: 4,
    maxLength: 20,
    allowSpecialChars: false,
    forbidSpaces: true,
    forbidStartingNumber: true,
    blockedUsernames: ['admin', 'root', 'system', 'moderator', 'support'],
    details: true
  });
  
  if (!usernameResult.valid) {
    errors.username = usernameResult.errors;
  }
  
  return {
    valid: Object.keys(errors).length === 0,
    errors
  };
}

// Usage
const result = validateRegistration({
  email: '[email protected]',
  password: 'MySecure@Pass123',
  username: 'johndoe'
});

if (!result.valid) {
  console.log('Validation errors:', result.errors);
} else {
  console.log('Registration valid! Proceed with signup.');
}

Login Form Validation

Validate login credentials with flexible identifier support (email or username).
import { isEmail, isUsername } from 'validauth';

function validateLogin(identifier, password) {
  const errors = {};
  
  // Check if identifier is email or username format
  const isEmailFormat = identifier.includes('@');
  
  if (isEmailFormat) {
    // Validate as email with relaxed rules for login
    const emailResult = isEmail(identifier, {
      requireTLD: true,
      details: true
    });
    
    if (!emailResult.valid) {
      errors.identifier = 'Invalid email address';
    }
  } else {
    // Validate as username with minimal rules
    const usernameResult = isUsername(identifier, {
      minLength: 1, // Accept any length for login
      maxLength: 50,
      details: true
    });
    
    if (!usernameResult.valid) {
      errors.identifier = 'Invalid username';
    }
  }
  
  // Basic password presence check (don't validate strength on login)
  if (!password || password.length === 0) {
    errors.password = 'Password is required';
  }
  
  return {
    valid: Object.keys(errors).length === 0,
    errors
  };
}

// Usage
const result = validateLogin('[email protected]', 'MyPassword123');
if (result.valid) {
  // Proceed with authentication
  authenticateUser(identifier, password);
}
For login validation, use relaxed rules compared to registration. Only verify format validity, not strength requirements.

Password Reset Flow

Implement a secure password reset with validation against username and old password.
1

Validate New Password

import { isPassword } from 'validauth';

function validateNewPassword(newPassword, userData) {
  const { username, email } = userData;
  
  // Validate password strength
  const result = isPassword(newPassword, {
    minLength: 12,
    maxLength: 128,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSymbols: true,
    forbidCommonPasswords: true,
    details: true
  });
  
  if (!result.valid) {
    return result;
  }
  
  // Additional security checks
  const additionalErrors = [];
  
  // Check if password contains username
  if (newPassword.toLowerCase().includes(username.toLowerCase())) {
    additionalErrors.push('Password cannot contain your username');
  }
  
  // Check if password contains email local part
  const emailLocal = email.split('@')[0];
  if (newPassword.toLowerCase().includes(emailLocal.toLowerCase())) {
    additionalErrors.push('Password cannot contain your email address');
  }
  
  if (additionalErrors.length > 0) {
    return {
      valid: false,
      errors: additionalErrors
    };
  }
  
  return { valid: true };
}
2

Verify Password Match

import { isPasswordMatch } from 'validauth';

function validatePasswordConfirmation(password, confirmPassword) {
  const result = isPasswordMatch(password, confirmPassword, {
    details: true
  });
  
  if (!result.match) {
    return {
      valid: false,
      errors: ['Passwords do not match']
    };
  }
  
  return { valid: true };
}
3

Complete Reset Function

async function handlePasswordReset(userId, newPassword, confirmPassword) {
  // Fetch user data
  const userData = await getUserData(userId);
  
  // Validate new password
  const passwordValidation = validateNewPassword(newPassword, userData);
  if (!passwordValidation.valid) {
    return {
      success: false,
      errors: passwordValidation.errors
    };
  }
  
  // Validate password confirmation
  const matchValidation = validatePasswordConfirmation(newPassword, confirmPassword);
  if (!matchValidation.valid) {
    return {
      success: false,
      errors: matchValidation.errors
    };
  }
  
  // Update password in database
  await updateUserPassword(userId, newPassword);
  
  return { success: true };
}

Social Media Registration

Validate social media signup with username handles and email verification.
import { isEmail, isUsername } from 'validauth';

function validateSocialSignup(email, handle) {
  const errors = {};
  
  // Email validation with plus addressing allowed
  const emailResult = isEmail(email, {
    allowPlusAddressing: true,
    requireTLD: true,
    details: true
  });
  
  if (!emailResult.valid) {
    errors.email = emailResult.errors;
  }
  
  // Username/handle validation for social platforms
  const handleResult = isUsername(handle, {
    minLength: 3,
    maxLength: 30,
    allowSpecialChars: false,
    forbidSpaces: true,
    forbidStartingNumber: true,
    blockedUsernames: [
      'admin', 'support', 'help', 'official',
      'staff', 'moderator', 'mod', 'owner'
    ],
    details: true
  });
  
  if (!handleResult.valid) {
    errors.handle = handleResult.errors;
  }
  
  return {
    valid: Object.keys(errors).length === 0,
    errors,
    data: {
      email: emailResult.email,
      handle: handleResult.username
    }
  };
}

// Usage
const result = validateSocialSignup('[email protected]', 'cooldeveloper');
if (result.valid) {
  createSocialAccount(result.data);
}

Real-Time Password Strength Indicator

Provide live feedback to users as they create passwords.
import { getPasswordStrength, isPassword } from 'validauth';

function createPasswordStrengthIndicator(inputElement, strengthElement) {
  inputElement.addEventListener('input', (e) => {
    const password = e.target.value;
    
    if (password.length === 0) {
      strengthElement.textContent = '';
      return;
    }
    
    // Get strength analysis
    const strength = getPasswordStrength(password, { details: true });
    
    // Update UI based on strength
    strengthElement.textContent = `Strength: ${strength.strength.toUpperCase()} (${strength.score}/100)`;
    strengthElement.className = `strength-indicator ${strength.strength}`;
    
    // Show crack time estimate
    const crackTimeElement = document.getElementById('crack-time');
    crackTimeElement.textContent = `Estimated crack time: ${strength.crackTimeDisplay}`;
    
    // Validate against requirements
    const validation = isPassword(password, {
      minLength: 10,
      requireSymbols: true,
      forbidCommonPasswords: true,
      details: true
    });
    
    // Display specific requirement errors
    const errorsElement = document.getElementById('password-errors');
    if (!validation.valid) {
      errorsElement.innerHTML = validation.errors
        .map(error => `<li>${error}</li>`)
        .join('');
    } else {
      errorsElement.innerHTML = '<li class="success">All requirements met!</li>';
    }
  });
}

// Usage
const passwordInput = document.getElementById('password');
const strengthIndicator = document.getElementById('strength');
createPasswordStrengthIndicator(passwordInput, strengthIndicator);

Multi-Step Form Validation

Validate authentication forms across multiple steps with state management.
import { isEmail, isPassword, isUsername, isPasswordMatch } from 'validauth';

class MultiStepRegistration {
  constructor() {
    this.currentStep = 1;
    this.formData = {
      email: '',
      username: '',
      password: '',
      confirmPassword: ''
    };
    this.errors = {};
  }
  
  validateStep(step) {
    this.errors = {};
    
    switch(step) {
      case 1:
        // Validate email
        const emailResult = isEmail(this.formData.email, {
          allowPlusAddressing: false,
          blockedDomains: ['tempmail.com', 'throwaway.email'],
          details: true
        });
        if (!emailResult.valid) {
          this.errors.email = emailResult.errors;
        }
        break;
        
      case 2:
        // Validate username
        const usernameResult = isUsername(this.formData.username, {
          minLength: 4,
          maxLength: 20,
          forbidStartingNumber: true,
          blockedUsernames: ['admin', 'root', 'system'],
          details: true
        });
        if (!usernameResult.valid) {
          this.errors.username = usernameResult.errors;
        }
        break;
        
      case 3:
        // Validate password
        const passwordResult = isPassword(this.formData.password, {
          minLength: 10,
          requireSymbols: true,
          forbidCommonPasswords: true,
          details: true
        });
        if (!passwordResult.valid) {
          this.errors.password = passwordResult.errors;
        }
        
        // Validate password match
        const matchResult = isPasswordMatch(
          this.formData.password,
          this.formData.confirmPassword,
          { details: true }
        );
        if (!matchResult.match) {
          this.errors.confirmPassword = matchResult.errors;
        }
        break;
    }
    
    return Object.keys(this.errors).length === 0;
  }
  
  nextStep() {
    if (this.validateStep(this.currentStep)) {
      this.currentStep++;
      return true;
    }
    return false;
  }
  
  previousStep() {
    if (this.currentStep > 1) {
      this.currentStep--;
    }
  }
  
  submit() {
    // Validate all steps before submission
    for (let step = 1; step <= 3; step++) {
      if (!this.validateStep(step)) {
        return {
          success: false,
          errors: this.errors,
          failedStep: step
        };
      }
    }
    
    return {
      success: true,
      data: this.formData
    };
  }
}

// Usage
const registration = new MultiStepRegistration();
registration.formData.email = '[email protected]';
if (registration.nextStep()) {
  console.log('Proceed to step 2');
}

Backend API Validation

Integrate ValidAuth with Express.js middleware for server-side validation.
import express from 'express';
import { isEmail, isPassword, isUsername } from 'validauth';

const app = express();
app.use(express.json());

// Middleware for registration validation
function validateRegistration(req, res, next) {
  const { email, password, username } = req.body;
  const errors = {};
  
  // Email validation
  const emailResult = isEmail(email, {
    allowPlusAddressing: false,
    blockedDomains: ['tempmail.com'],
    details: true
  });
  if (!emailResult.valid) {
    errors.email = emailResult.errors;
  }
  
  // Password validation
  const passwordResult = isPassword(password, {
    minLength: 10,
    requireSymbols: true,
    forbidCommonPasswords: true,
    details: true
  });
  if (!passwordResult.valid) {
    errors.password = passwordResult.errors;
  }
  
  // Username validation
  const usernameResult = isUsername(username, {
    minLength: 4,
    maxLength: 20,
    forbidStartingNumber: true,
    blockedUsernames: ['admin', 'root'],
    details: true
  });
  if (!usernameResult.valid) {
    errors.username = usernameResult.errors;
  }
  
  if (Object.keys(errors).length > 0) {
    return res.status(400).json({
      success: false,
      errors
    });
  }
  
  next();
}

// Registration endpoint
app.post('/api/register', validateRegistration, async (req, res) => {
  try {
    // Create user account
    const user = await createUser(req.body);
    res.json({ success: true, user });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3000);

OTP Verification Flow

Implement secure OTP validation with attempt limiting.
import { validateOTP, generateOTP } from 'validauth';

class OTPManager {
  constructor() {
    this.sessions = new Map();
  }
  
  // Generate and send OTP
  async sendOTP(userId, email) {
    const otp = generateOTP({ length: 6, details: true });
    
    // Store OTP session
    this.sessions.set(userId, {
      otp: otp.otp,
      attempts: 0,
      createdAt: Date.now(),
      expiresAt: Date.now() + (10 * 60 * 1000) // 10 minutes
    });
    
    // Send OTP via email (implement your email service)
    await sendEmailOTP(email, otp.otp);
    
    return { success: true };
  }
  
  // Verify OTP
  verifyOTP(userId, userOTP) {
    const session = this.sessions.get(userId);
    
    if (!session) {
      return {
        success: false,
        error: 'No OTP session found'
      };
    }
    
    // Check expiration
    if (Date.now() > session.expiresAt) {
      this.sessions.delete(userId);
      return {
        success: false,
        error: 'OTP has expired'
      };
    }
    
    // Increment attempts
    session.attempts++;
    
    // Validate OTP
    const result = validateOTP(userOTP, session.otp, {
      attempts: session.attempts,
      maxAttempts: 3,
      details: true
    });
    
    if (!result.valid) {
      // Check if max attempts reached
      if (session.attempts >= 3) {
        this.sessions.delete(userId);
        return {
          success: false,
          error: 'Maximum attempts exceeded. Please request a new OTP.',
          attemptsRemaining: 0
        };
      }
      
      return {
        success: false,
        error: 'Invalid OTP',
        attemptsRemaining: 3 - session.attempts
      };
    }
    
    // OTP valid, remove session
    this.sessions.delete(userId);
    
    return { success: true };
  }
}

// Usage
const otpManager = new OTPManager();

// Send OTP
await otpManager.sendOTP('user123', '[email protected]');

// Verify OTP
const result = otpManager.verifyOTP('user123', '123456');
if (result.success) {
  console.log('OTP verified successfully');
} else {
  console.log('Verification failed:', result.error);
}

XSS Protection for User Input

Validate and sanitize user-generated content to prevent XSS attacks.
import { isXSSSafe } from 'validauth';

function validateUserContent(content) {
  const result = isXSSSafe(content, { details: true });
  
  if (!result.safe) {
    return {
      valid: false,
      errors: ['Content contains potentially malicious code'],
      details: result.errors
    };
  }
  
  return { valid: true };
}

// Usage in a comment system
function submitComment(userId, commentText) {
  const validation = validateUserContent(commentText);
  
  if (!validation.valid) {
    return {
      success: false,
      message: 'Your comment contains invalid content',
      errors: validation.errors
    };
  }
  
  // Save comment to database
  saveComment(userId, commentText);
  
  return { success: true };
}
Always validate user input on both client and server side. Client-side validation improves UX, but server-side validation is essential for security.

Build docs developers (and LLMs) love