317 lines
11 KiB
TypeScript
317 lines
11 KiB
TypeScript
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from 'libphonenumber-js/max';
|
|
import {
|
|
COUNTRY_CODES,
|
|
getCountryRuleByDialCode,
|
|
getCountryRuleByName,
|
|
getCountryRuleByIso,
|
|
DEFAULT_COUNTRY,
|
|
} 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 mobile phone number according to country telecom numbering plans.
|
|
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07).
|
|
*/
|
|
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 symbols
|
|
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: prioritize explicit country name, fallback to dialCode
|
|
let rule = country ? getCountryRuleByName(country) : undefined;
|
|
if ((!rule || rule.country === 'Other') && dialCode) {
|
|
rule = getCountryRuleByDialCode(dialCode, country);
|
|
}
|
|
if (!rule) {
|
|
rule = DEFAULT_COUNTRY;
|
|
}
|
|
|
|
const iso2 = rule.iso2 || 'IN';
|
|
|
|
// Extract national digits without dial code prefix
|
|
let nationalDigits = allDigits;
|
|
const dialDigits = rule.code.replace(/\D/g, '');
|
|
if (trimmed.startsWith('+')) {
|
|
if (allDigits.startsWith(dialDigits)) {
|
|
nationalDigits = allDigits.slice(dialDigits.length);
|
|
}
|
|
} else if (allDigits.startsWith(dialDigits) && allDigits.length > rule.maxLength) {
|
|
nationalDigits = allDigits.slice(dialDigits.length);
|
|
}
|
|
|
|
const digitsWithoutTrunk0 = nationalDigits.startsWith('0') && iso2 !== 'IT'
|
|
? nationalDigits.replace(/^0+/, '')
|
|
: nationalDigits;
|
|
|
|
// 1. Enforce length validation FIRST so digit count errors take precedence over prefix errors
|
|
if (iso2 === 'IN') {
|
|
if (nationalDigits.length !== 10) {
|
|
return 'India mobile number must be exactly 10 digits.';
|
|
}
|
|
if (!/^[6-9]/.test(nationalDigits)) {
|
|
return 'India mobile number must begin with 6, 7, 8, or 9.';
|
|
}
|
|
} else if (iso2 === 'FR') {
|
|
if (nationalDigits.length < 9) {
|
|
return 'France mobile number is too short (must be 9 digits, or 10 digits with 0).';
|
|
}
|
|
if (nationalDigits.length > 10 || (nationalDigits.length === 10 && !nationalDigits.startsWith('0'))) {
|
|
return 'France mobile number cannot exceed 9 digits (or 10 digits with leading 0).';
|
|
}
|
|
if (!/^[67]/.test(digitsWithoutTrunk0)) {
|
|
return 'France mobile number must begin with 06 or 07 (or 6 or 7).';
|
|
}
|
|
} else if (iso2 === 'GB') {
|
|
if (digitsWithoutTrunk0.length < 10) {
|
|
return 'United Kingdom mobile number is too short (must be 10 digits, or 11 digits with 0).';
|
|
}
|
|
if (digitsWithoutTrunk0.length > 10) {
|
|
return 'United Kingdom mobile number cannot exceed 10 digits (or 11 digits with leading 0).';
|
|
}
|
|
if (!/^7/.test(digitsWithoutTrunk0)) {
|
|
return 'United Kingdom mobile number must begin with 07 (or 7).';
|
|
}
|
|
} else {
|
|
// General length check for other countries
|
|
if (rule.minLength === rule.maxLength) {
|
|
if (digitsWithoutTrunk0.length !== rule.minLength && nationalDigits.length !== rule.minLength) {
|
|
return `${rule.country} mobile number must be exactly ${rule.minLength} digits.`;
|
|
}
|
|
} else {
|
|
if (digitsWithoutTrunk0.length < rule.minLength && nationalDigits.length < rule.minLength) {
|
|
return `${rule.country} mobile number is too short (min ${rule.minLength} digits).`;
|
|
}
|
|
if (digitsWithoutTrunk0.length > rule.maxLength) {
|
|
return `${rule.country} mobile number cannot exceed ${rule.maxLength} digits.`;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Validate telecom numbering rules with libphonenumber-js
|
|
const candidate = trimmed.startsWith('+') ? trimmed : `${rule.code}${nationalDigits}`;
|
|
const parsed = parsePhoneNumberFromString(candidate, iso2);
|
|
|
|
if (parsed && parsed.isValid()) {
|
|
const numberType = parsed.getType();
|
|
if (numberType === 'FIXED_LINE') {
|
|
return `Please enter a valid mobile number for ${rule.country}.`;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
return `Please enter a valid mobile number for ${rule.country} (e.g. ${rule.placeholder}).`;
|
|
};
|
|
|
|
export const isValidPhoneNumber = (
|
|
val?: string | null,
|
|
dialCode?: string,
|
|
country?: string
|
|
): boolean => {
|
|
return validatePhoneNumber(val, dialCode, country) === null;
|
|
};
|
|
|
|
/**
|
|
* Splits a full phone number into dialCode, country, and localDigits
|
|
*/
|
|
export const parsePhoneNumber = (
|
|
fullPhone?: string | null,
|
|
fallbackCountry = 'India'
|
|
): { country: string; dialCode: string; localDigits: string; iso2: LibCountryCode } => {
|
|
const defaultRule = getCountryRuleByName(fallbackCountry) || DEFAULT_COUNTRY;
|
|
if (!fullPhone || !fullPhone.trim()) {
|
|
return {
|
|
country: defaultRule.country,
|
|
dialCode: defaultRule.code,
|
|
localDigits: '',
|
|
iso2: defaultRule.iso2,
|
|
};
|
|
}
|
|
|
|
const trimmed = fullPhone.trim();
|
|
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
|
|
|
|
if (parsed) {
|
|
const matchedRule = parsed.country
|
|
? getCountryRuleByIso(parsed.country)
|
|
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
|
|
|
|
return {
|
|
country: matchedRule.country,
|
|
dialCode: `+${parsed.countryCallingCode}`,
|
|
localDigits: parsed.nationalNumber,
|
|
iso2: matchedRule.iso2,
|
|
};
|
|
}
|
|
|
|
// Fallback regex match from longest dial code
|
|
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
|
|
|
// If fallbackCountry is specified and matches the prefix, prioritize it
|
|
if (fallbackCountry && trimmed.startsWith(defaultRule.code)) {
|
|
const rawLocal = trimmed.slice(defaultRule.code.length).replace(/\D/g, '');
|
|
return {
|
|
country: defaultRule.country,
|
|
dialCode: defaultRule.code,
|
|
localDigits: rawLocal.slice(0, defaultRule.maxLength),
|
|
iso2: defaultRule.iso2,
|
|
};
|
|
}
|
|
|
|
const matched = sorted.find((c) => trimmed.startsWith(c.code));
|
|
if (matched) {
|
|
const rawLocal = trimmed.slice(matched.code.length).replace(/\D/g, '');
|
|
return {
|
|
country: matched.country,
|
|
dialCode: matched.code,
|
|
localDigits: rawLocal.slice(0, matched.maxLength),
|
|
iso2: matched.iso2,
|
|
};
|
|
}
|
|
|
|
const rawDigits = trimmed.replace(/\D/g, '');
|
|
return {
|
|
country: defaultRule.country,
|
|
dialCode: defaultRule.code,
|
|
localDigits: rawDigits.slice(0, defaultRule.maxLength),
|
|
iso2: defaultRule.iso2,
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>),
|
|
* automatically stripping any national trunk '0' where appropriate.
|
|
*/
|
|
export const formatE164Phone = (dialCode: string, localDigits: string, country?: string): string => {
|
|
if (!localDigits || !localDigits.trim()) return '';
|
|
const rule = country ? getCountryRuleByName(country) : getCountryRuleByDialCode(dialCode, country);
|
|
const rawDigits = localDigits.replace(/\D/g, '');
|
|
if (!rawDigits) return '';
|
|
|
|
const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`;
|
|
const candidate = localDigits.startsWith('+') ? localDigits : `${code}${rawDigits}`;
|
|
|
|
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
|
|
if (parsed && parsed.isValid()) {
|
|
return parsed.format('E.164');
|
|
}
|
|
|
|
// Fallback: If starts with trunk 0 and country is not one that keeps trunk 0 (like Italy)
|
|
let cleanLocal = rawDigits;
|
|
if (rule.iso2 !== 'IT' && cleanLocal.startsWith('0')) {
|
|
cleanLocal = cleanLocal.replace(/^0+/, '');
|
|
}
|
|
|
|
return `${code}${cleanLocal}`;
|
|
};
|
|
|
|
/**
|
|
* 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);
|
|
|
|
const parsed = parsePhoneNumber(trimmed, oldRule.country);
|
|
const bounded = parsed.localDigits.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.
|
|
*/
|
|
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;
|
|
};
|