Validation Functions
Email Validation
Validate email addresses using regex pattern
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
Phone Number Validation
Validate US phone numbers (10 digits)
function validatePhone(phone) {
const regex = /^\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$/;
return regex.test(phone);
}
Required Field
Check if field is not empty
function validateRequired(value) {
return value.trim().length > 0;
}
Length Validation
Validate min and max character length
function validateLength(value, min, max) {
const length = value.trim().length;
return length >= min && length <= max;
}
Password Strength
Check password strength (weak/medium/strong)
function checkPasswordStrength(password) {
let strength = 0;
if (password.length >= 8) strength++;
if (/[a-z]/.test(password)) strength++;
if (/[A-Z]/.test(password)) strength++;
if (/[0-9]/.test(password)) strength++;
if (/[^a-zA-Z0-9]/.test(password)) strength++;
if (strength <= 2) return 'weak';
if (strength <= 4) return 'medium';
return 'strong';
}
Credit Card (Luhn Algorithm)
Validate credit card numbers using Luhn algorithm
function validateCreditCard(cardNumber) {
const digits = cardNumber.replace(/\D/g, '');
let sum = 0;
let isEven = false;
for (let i = digits.length - 1; i >= 0; i--) {
let digit = parseInt(digits[i]);
if (isEven) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
isEven = !isEven;
}
return sum % 10 === 0;
}
URL Validation
Validate URLs with http/https protocol
function validateURL(url) {
const regex = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
return regex.test(url);
}
Match Fields (Password Confirm)
Check if two fields match (useful for password confirmation)
function validateMatch(value1, value2) {
return value1 === value2 && value1.length > 0;
}