Quick Start Guide
Learn how to validate authentication inputs with ValidAuth through practical, real-world examples.
Basic Validation
The simplest way to use ValidAuth is with boolean validation - just pass your input and get true or false:
import { isEmail , isPassword , isUsername } from 'validauth' ;
// Email validation
const validEmail = isEmail ( '[email protected] ' ); // true
const invalidEmail = isEmail ( 'not-an-email' ); // false
// Password validation
const strongPassword = isPassword ( 'MyP@ssw0rd123' ); // true
const weakPassword = isPassword ( 'weak' ); // false
// Username validation
const validUsername = isUsername ( 'johndoe' ); // true
const shortUsername = isUsername ( 'ab' ); // false
By default, all validators use secure, sensible defaults. Passwords require uppercase, lowercase, numbers, and symbols. Usernames must be 3-30 characters. Emails must be RFC-compliant.
Detailed Validation
For production applications, you’ll want detailed error messages to show users exactly what’s wrong:
import { isEmail , isPassword , isUsername } from 'validauth' ;
// Get detailed validation results
const emailResult = isEmail ( 'invalid@' , { details: true });
console . log ( emailResult );
// {
// valid: false,
// errors: ['Domain cannot be empty'],
// email: 'invalid@',
// localPart: 'invalid',
// domain: ''
// }
const passwordResult = isPassword ( 'weak' , { details: true });
console . log ( passwordResult );
// {
// 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 number',
// 'Password must contain at least one symbol'
// ],
// password: 'weak'
// }
const usernameResult = isUsername ( 'ab' , { details: true });
console . log ( usernameResult );
// {
// valid: false,
// errors: ['Username must be at least 3 characters long'],
// username: 'ab'
// }
The details: true option returns an object with valid (boolean), errors (array or null), and additional metadata specific to each validator.
Complete Registration Example
Here’s a complete example of validating a registration form with custom rules:
Import Validators
import { isEmail , isPassword , isUsername } from 'validauth' ;
Create Validation Function
function validateRegistration ( email , password , username ) {
const errors = {};
// Validate email - block temporary email services
const emailResult = isEmail ( email , {
allowPlusAddressing: false ,
blockedDomains: [ 'tempmail.com' , 'throwaway.email' , '10minutemail.com' ],
details: true
});
if ( ! emailResult . valid ) {
errors . email = emailResult . errors ;
}
// Validate password - require strong passwords
const passwordResult = isPassword ( password , {
minLength: 10 ,
requireSymbols: true ,
forbidCommonPasswords: true , // Block 'password123', etc.
details: true
});
if ( ! passwordResult . valid ) {
errors . password = passwordResult . errors ;
}
// Validate username - reserve admin names
const usernameResult = isUsername ( username , {
minLength: 4 ,
maxLength: 20 ,
forbidStartingNumber: true ,
blockedUsernames: [ 'admin' , 'root' , 'system' , 'moderator' ],
details: true
});
if ( ! usernameResult . valid ) {
errors . username = usernameResult . errors ;
}
return {
valid: Object . keys ( errors ). length === 0 ,
errors
};
}
Use the Validator
const result = validateRegistration (
'[email protected] ' ,
'MySecure@Pass2024' ,
'johndoe'
);
if ( ! result . valid ) {
console . log ( 'Validation errors:' , result . errors );
// {
// email: null,
// password: null,
// username: null
// }
} else {
console . log ( 'All valid! Proceed with registration.' );
// Create user account...
}
Custom Validation Rules
Each validator accepts extensive options for customization:
Email Options
Password Options
Username Options
const result = isEmail ( '[email protected] ' , {
allowPlusAddressing: true , // Allow [email protected]
requireTLD: true , // Require .com, .org, etc.
blockedDomains: [], // Block specific domains
details: false // Return detailed info
});
Password Strength Checking
ValidAuth includes a password strength calculator that returns a score and estimated crack time:
import { getPasswordStrength } from 'validauth' ;
// Simple strength check
const strength = getPasswordStrength ( 'MyP@ssw0rd123' );
console . log ( strength ); // 'medium'
// Detailed strength analysis
const details = getPasswordStrength ( 'MyP@ssw0rd123' , { details: true });
console . log ( details );
// {
// strength: 'medium',
// score: 50,
// estimatedCrackTimeInYears: 10000,
// crackTimeDisplay: '10000 years'
// }
How is password strength calculated?
ValidAuth calculates password strength based on:
Length : Longer passwords score higher (8+ = 10pts, 12+ = 20pts, 16+ = 30pts, 20+ = 40pts)
Character variety : Lowercase, uppercase, numbers, symbols (10pts each)
Complexity bonus : Extra points for combining length and variety (up to 20pts)
Common password penalty : Score of 0 for passwords in the common password database
Final scores:
0-39 : Weak
40-69 : Medium
70-100 : Strong
Password Matching
Validate that two passwords match (useful for confirmation fields):
import { isPasswordMatch } from 'validauth' ;
const password = 'MySecurePass123!' ;
const confirmPassword = 'MySecurePass123!' ;
// Simple boolean check
const match = isPasswordMatch ( password , confirmPassword );
console . log ( match ); // true
// Detailed check
const result = isPasswordMatch ( password , 'DifferentPass' , { details: true });
console . log ( result );
// {
// match: false,
// errors: ['Passwords do not match']
// }
Real-World Examples
Accept either email or username as login identifier:
import { isEmail , isUsername } from 'validauth' ;
function validateLogin ( identifier , password ) {
// Check if identifier looks like an email
const isEmailFormat = identifier . includes ( '@' );
if ( isEmailFormat ) {
// Validate as email with minimal requirements
const emailValid = isEmail ( identifier , { details: true });
if ( ! emailValid . valid ) {
return { valid: false , error: 'Invalid email address' };
}
} else {
// Validate as username with minimal requirements
const usernameValid = isUsername ( identifier , {
minLength: 1 ,
details: true
});
if ( ! usernameValid . valid ) {
return { valid: false , error: 'Invalid username' };
}
}
// Check password exists (don't validate strength on login)
if ( ! password || password . length === 0 ) {
return { valid: false , error: 'Password is required' };
}
return { valid: true };
}
// Usage
const loginResult = validateLogin ( '[email protected] ' , 'userPassword' );
if ( loginResult . valid ) {
// Proceed with authentication
}
Password Reset
Validate new password and ensure it doesn’t contain the username:
import { isPassword } from 'validauth' ;
function validatePasswordReset ( newPassword , username , oldPassword ) {
// Validate password strength
const passwordResult = isPassword ( newPassword , {
minLength: 12 ,
requireSymbols: true ,
forbidCommonPasswords: true ,
details: true
});
if ( ! passwordResult . valid ) {
return {
valid: false ,
errors: passwordResult . errors
};
}
// Check if new password is same as old password
if ( newPassword === oldPassword ) {
return {
valid: false ,
errors: [ 'New password must be different from old password' ]
};
}
// Check if password contains username
if ( newPassword . toLowerCase (). includes ( username . toLowerCase ())) {
return {
valid: false ,
errors: [ 'Password cannot contain your username' ]
};
}
return { valid: true };
}
Validate usernames for social media with flexible rules:
import { isUsername } from 'validauth' ;
function validateHandle ( handle ) {
return isUsername ( handle , {
minLength: 3 ,
maxLength: 30 ,
allowSpecialChars: false ,
forbidSpaces: true ,
forbidStartingNumber: true ,
blockedUsernames: [
'admin' , 'support' , 'help' , 'official' ,
'staff' , 'team' , 'news' , 'press'
],
details: true
});
}
const result = validateHandle ( 'johndoe_2024' );
if ( result . valid ) {
console . log ( 'Handle is available!' );
} else {
console . log ( 'Handle errors:' , result . errors );
}
These examples show client-side validation. Always validate user input on the server side as well for security. Client-side validation can be bypassed.
Framework Integration
React
Vue
Node.js/Express
import { useState } from 'react' ;
import { isEmail , isPassword } from 'validauth' ;
function RegistrationForm () {
const [ email , setEmail ] = useState ( '' );
const [ password , setPassword ] = useState ( '' );
const [ errors , setErrors ] = useState ({});
const handleEmailChange = ( e ) => {
const value = e . target . value ;
setEmail ( value );
const result = isEmail ( value , { details: true });
if ( ! result . valid ) {
setErrors ( prev => ({ ... prev , email: result . errors }));
} else {
setErrors ( prev => ({ ... prev , email: null }));
}
};
const handlePasswordChange = ( e ) => {
const value = e . target . value ;
setPassword ( value );
const result = isPassword ( value , {
minLength: 10 ,
forbidCommonPasswords: true ,
details: true
});
if ( ! result . valid ) {
setErrors ( prev => ({ ... prev , password: result . errors }));
} else {
setErrors ( prev => ({ ... prev , password: null }));
}
};
return (
< form >
< input
type = "email"
value = { email }
onChange = { handleEmailChange }
placeholder = "Email"
/>
{ errors . email && (
< div className = "error" > { errors . email . join ( ', ' ) } </ div >
) }
< input
type = "password"
value = { password }
onChange = { handlePasswordChange }
placeholder = "Password"
/>
{ errors . password && (
< div className = "error" > { errors . password . join ( ', ' ) } </ div >
) }
</ form >
);
}
< script setup >
import { ref , computed } from 'vue' ;
import { isEmail , isPassword , isUsername } from 'validauth' ;
const email = ref ( '' );
const password = ref ( '' );
const username = ref ( '' );
const errors = ref ({});
const validateEmail = () => {
const result = isEmail ( email . value , { details: true });
if ( ! result . valid ) {
errors . value . email = result . errors ;
} else {
delete errors . value . email ;
}
};
const validatePassword = () => {
const result = isPassword ( password . value , {
minLength: 10 ,
forbidCommonPasswords: true ,
details: true
});
if ( ! result . valid ) {
errors . value . password = result . errors ;
} else {
delete errors . value . password ;
}
};
const isFormValid = computed (() => {
return Object . keys ( errors . value ). length === 0 &&
email . value && password . value && username . value ;
});
</ script >
< template >
< form >
< input
v-model = " email "
@ blur = " validateEmail "
type = "email"
placeholder = "Email"
/>
< div v-if = " errors . email " class = "error" >
{{ errors . email . join ( ', ' ) }}
</ div >
< input
v-model = " password "
@ blur = " validatePassword "
type = "password"
placeholder = "Password"
/>
< div v-if = " errors . password " class = "error" >
{{ errors . password . join ( ', ' ) }}
</ div >
< button : disabled = " ! isFormValid " > Register </ button >
</ form >
</ template >
import express from 'express' ;
import { isEmail , isPassword , isUsername } from 'validauth' ;
const app = express ();
app . use ( express . json ());
app . post ( '/api/register' , ( req , res ) => {
const { email , password , username } = req . body ;
const errors = {};
// Validate email
const emailResult = isEmail ( email , {
blockedDomains: [ 'tempmail.com' , 'throwaway.email' ],
details: true
});
if ( ! emailResult . valid ) {
errors . email = emailResult . errors ;
}
// Validate password
const passwordResult = isPassword ( password , {
minLength: 10 ,
forbidCommonPasswords: true ,
details: true
});
if ( ! passwordResult . valid ) {
errors . password = passwordResult . errors ;
}
// Validate username
const usernameResult = isUsername ( username , {
blockedUsernames: [ 'admin' , 'root' ],
details: true
});
if ( ! usernameResult . valid ) {
errors . username = usernameResult . errors ;
}
if ( Object . keys ( errors ). length > 0 ) {
return res . status ( 400 ). json ({ errors });
}
// Proceed with user creation
res . json ({ success: true , message: 'User registered successfully' });
});
app . listen ( 3000 );
Next Steps
Now that you understand the basics, explore specific validators:
Email Validator Deep dive into email validation options and edge cases
Password Validator Learn about password security and strength checking
Username Validator Configure username rules for your application
OTP Validator Implement two-factor authentication with OTP validation