acupedia-store-ui/src/utils/validation.ts

203 lines
6.9 KiB
TypeScript

import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../constants/countries';
/**
* Strips non-numeric / non-phone characters from text in real-time
* If maxLength is provided, strictly restricts digit length
* If allowPlus is false, strips any '+' symbols as well (for local number inputs)
*/
export const cleanPhoneInput = (text: string, maxLength = 15, allowPlus = true): string => {
const trimmedStart = text.trimStart();
const hasPlus = allowPlus && trimmedStart.startsWith('+');
const rest = hasPlus ? trimmedStart.slice(1) : text;
const digitsOnly = rest.replace(/\D/g, '');
const boundedDigits = maxLength ? digitsOnly.slice(0, maxLength) : digitsOnly;
return hasPlus ? `+${boundedDigits}` : boundedDigits;
};
/**
* Validates phone number according to country rules (e.g. India = exactly 10 digits)
* Strictly disallows alphabetic characters and invalid symbols
*/
export const validatePhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): string | null => {
if (!val || !val.trim()) return null;
const trimmed = val.trim();
// Explicitly disallow alphabetic characters
if (/[a-zA-Z]/.test(trimmed)) {
return 'Phone number cannot contain alphabetic characters.';
}
// Strictly disallow hyphens, dashes, and invalid characters
if (/[\-()_]/.test(trimmed)) {
return 'Phone number cannot contain hyphens or special symbols.';
}
// Strictly enforce numeric digits with optional leading '+' and whitespace
if (!/^\+?[\d\s]+$/.test(trimmed)) {
return 'Please enter a valid phone number containing only numeric digits.';
}
const allDigits = trimmed.replace(/\D/g, '');
if (allDigits.length === 0) {
return 'Please enter a valid phone number with numeric digits.';
}
// Resolve country rule by dial code or country name
let rule = dialCode ? getCountryRuleByDialCode(dialCode) : undefined;
if ((!rule || rule.country === 'Other') && country) {
rule = getCountryRuleByName(country);
}
// Default to India if no specific rule resolved and dial code is +91 or country is India
if (!rule || rule.country === 'Other') {
if (dialCode === '+91' || (country && country.toLowerCase() === 'india')) {
rule = getCountryRuleByDialCode('+91');
}
}
if (rule && rule.country !== 'Other') {
const dialDigits = rule.code.replace(/\D/g, '');
let localDigits = allDigits;
// If formatted with country code (e.g. +919876543210 or 919876543210 where total length > rule.maxLength), strip country prefix
if (
(trimmed.startsWith('+') || allDigits.length > rule.maxLength) &&
allDigits.startsWith(dialDigits) &&
allDigits.length === dialDigits.length + rule.minLength
) {
localDigits = allDigits.slice(dialDigits.length);
}
if (rule.minLength === rule.maxLength) {
if (localDigits.length !== rule.minLength) {
return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
}
} else {
if (localDigits.length < rule.minLength) {
return `${rule.country} phone number must be at least ${rule.minLength} digits.`;
}
if (localDigits.length > rule.maxLength) {
return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`;
}
}
return null;
}
// General fallback ITU E.164
if (allDigits.length < 7) {
return 'Phone number must contain at least 7 digits.';
}
if (allDigits.length > 15) {
return 'Phone number cannot exceed 15 digits.';
}
return null;
};
export const isValidPhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): boolean => {
return validatePhoneNumber(val, dialCode, country) === null;
};
/**
* Updates the dial code prefix of an existing phone number when country changes.
* Automatically clamps remaining digits to the new country's maxLength.
*/
export const updatePhoneDialCode = (
currentPhone: string,
oldCountry: string,
newCountry: string
): string => {
const trimmed = currentPhone.trim();
if (!trimmed) return '';
const oldRule = getCountryRuleByName(oldCountry);
const newRule = getCountryRuleByName(newCountry);
let nationalDigits = '';
if (trimmed.startsWith('+')) {
const matched = [...COUNTRY_CODES]
.sort((a, b) => b.code.length - a.code.length)
.find((c) => trimmed.startsWith(c.code));
if (matched) {
nationalDigits = trimmed.slice(matched.code.length).replace(/\D/g, '');
} else {
nationalDigits = trimmed.replace(/^\+/, '').replace(/\D/g, '');
}
} else {
const oldDialDigits = oldRule.code.replace(/\D/g, '');
const rawDigits = trimmed.replace(/\D/g, '');
if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldDialDigits.length) {
nationalDigits = rawDigits.slice(oldDialDigits.length);
} else {
nationalDigits = rawDigits;
}
}
const bounded = nationalDigits.slice(0, newRule.maxLength);
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
};
export const SPECIAL_CHAR_REGEX = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?`~]/;
/**
* Validates password strength consistently across registration, profile change, and password reset:
* - Minimum 8 characters
* - No spaces (whitespace strictly disallowed)
* - At least one uppercase letter
* - At least one number
* - No emojis
* - At least one special character from standard symbol set
*/
export const validatePassword = (password: string, fieldName = 'Password'): string | null => {
if (!password) {
return `${fieldName} is required.`;
}
if (password.length < 8) {
return `${fieldName} must be at least 8 characters long.`;
}
if (/\s/.test(password)) {
return `${fieldName} must not contain spaces.`;
}
if (!/[A-Z]/.test(password)) {
return `${fieldName} must contain at least one uppercase letter.`;
}
if (!/[0-9]/.test(password)) {
return `${fieldName} must contain at least one number.`;
}
if (/\p{Extended_Pictographic}/u.test(password)) {
return `${fieldName} must not contain emojis.`;
}
if (!SPECIAL_CHAR_REGEX.test(password)) {
return `${fieldName} must contain at least one special character.`;
}
return null;
};
/**
* RFC 5322 & RFC 1035 compliant email validation regex.
* Disallows invalid domain characters (e.g. + in domain like +gmail+.com, consecutive dots, leading/trailing hyphens)
* while properly accepting plus-addressing in local-part (e.g. sanskar+sarak@gmail.com).
*/
export const EMAIL_REGEX = /^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
export const validateEmail = (email?: string | null): string | null => {
if (!email || !email.trim()) {
return 'Email address is required.';
}
if (!EMAIL_REGEX.test(email.trim())) {
return 'Please enter a valid email address.';
}
return null;
};
export const isValidEmail = (email?: string | null): boolean => {
return validateEmail(email) === null;
};