refactor(auth): derive country phone rules dynamically from libphonenumber-js
This commit is contained in:
parent
f119e7d72f
commit
d9d1487265
|
|
@ -1,11 +1,18 @@
|
|||
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from "libphonenumber-js/max";
|
||||
import {
|
||||
getCountries,
|
||||
getCountryCallingCode,
|
||||
getExampleNumber,
|
||||
parsePhoneNumberFromString,
|
||||
type CountryCode as LibCountryCode,
|
||||
} from "libphonenumber-js/max";
|
||||
import metadata from "libphonenumber-js/metadata.max.json";
|
||||
import examples from "libphonenumber-js/examples.mobile.json";
|
||||
|
||||
export interface CountryCode {
|
||||
iso2: LibCountryCode;
|
||||
code: string;
|
||||
label: string;
|
||||
country: string;
|
||||
currency: string;
|
||||
minLength: number;
|
||||
maxLength: number;
|
||||
placeholder: string;
|
||||
|
|
@ -13,399 +20,334 @@ export interface CountryCode {
|
|||
example?: string;
|
||||
}
|
||||
|
||||
type CountryMetadataTuple = readonly unknown[];
|
||||
|
||||
interface MetadataJson {
|
||||
countries: Record<string, CountryMetadataTuple>;
|
||||
country_calling_codes: Record<string, string[]>;
|
||||
}
|
||||
|
||||
const typedMetadata = metadata as unknown as MetadataJson;
|
||||
|
||||
/** Converts an ISO 3166-1 alpha-2 code (e.g. "IN") into its Unicode flag emoji. */
|
||||
const isoToFlag = (iso2: string): string => {
|
||||
const upper = iso2.toUpperCase();
|
||||
if (!/^[A-Z]{2}$/.test(upper)) return "🏳️";
|
||||
return String.fromCodePoint(
|
||||
0x1f1e6 + upper.charCodeAt(0) - 65,
|
||||
0x1f1e6 + upper.charCodeAt(1) - 65
|
||||
);
|
||||
};
|
||||
|
||||
const regionDisplayNames =
|
||||
typeof Intl !== "undefined" && typeof Intl.DisplayNames === "function"
|
||||
? new Intl.DisplayNames(["en"], { type: "region" })
|
||||
: null;
|
||||
|
||||
const getRegionName = (iso2: string): string => {
|
||||
try {
|
||||
return regionDisplayNames?.of(iso2) || iso2;
|
||||
} catch {
|
||||
return iso2;
|
||||
}
|
||||
};
|
||||
|
||||
const buildCountryRule = (iso2: LibCountryCode): CountryCode => {
|
||||
const callingCode = getCountryCallingCode(iso2);
|
||||
const code = `+${callingCode}`;
|
||||
const flag = isoToFlag(iso2);
|
||||
const country = getRegionName(iso2);
|
||||
|
||||
const countryMeta = typedMetadata.countries[iso2];
|
||||
const mobileDesc = countryMeta?.[11] as unknown[] | undefined;
|
||||
const mobileTuple = mobileDesc?.[1] as [string, number[]?] | undefined;
|
||||
const generalLengths = countryMeta?.[3] as number[] | undefined;
|
||||
const mobileLengths = mobileTuple?.[1] ?? generalLengths ?? [7, 15];
|
||||
|
||||
const minLength = Math.min(...mobileLengths);
|
||||
const maxLength = Math.max(...mobileLengths);
|
||||
|
||||
const exampleNumber = getExampleNumber(iso2, examples);
|
||||
const example = exampleNumber?.nationalNumber;
|
||||
const placeholder =
|
||||
minLength === maxLength
|
||||
? `${minLength}-digit mobile number`
|
||||
: `${minLength}-${maxLength} digit mobile number`;
|
||||
|
||||
return {
|
||||
iso2,
|
||||
code,
|
||||
label: `${flag} ${code}`,
|
||||
country,
|
||||
minLength,
|
||||
maxLength,
|
||||
placeholder,
|
||||
example,
|
||||
};
|
||||
};
|
||||
|
||||
// Order primary country per calling code before secondary territories (e.g. US before AG for +1, GB before GG for +44).
|
||||
const isPrimaryForCallingCode = (iso2: LibCountryCode): boolean => {
|
||||
const callingCode = getCountryCallingCode(iso2);
|
||||
return typedMetadata.country_calling_codes[callingCode]?.[0] === iso2;
|
||||
};
|
||||
|
||||
const allCountries = getCountries();
|
||||
export const COUNTRY_CODES: CountryCode[] = [
|
||||
// South Asia
|
||||
{ iso2: "IN", code: "+91", label: "🇮🇳 +91", country: "India", currency: "INR", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["6", "7", "8", "9"], example: "98765 43210" },
|
||||
{ iso2: "PK", code: "+92", label: "🇵🇰 +92", country: "Pakistan", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["3"], example: "300 1234567" },
|
||||
{ iso2: "BD", code: "+880", label: "🇧🇩 +880", country: "Bangladesh", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["1"], example: "1712 345678" },
|
||||
{ iso2: "LK", code: "+94", label: "🇱🇰 +94", country: "Sri Lanka", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["7"], example: "71 234 5678" },
|
||||
{ iso2: "NP", code: "+977", label: "🇳🇵 +977", country: "Nepal", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["97", "98"], example: "9812 345678" },
|
||||
{ iso2: "BT", code: "+975", label: "🇧🇹 +975", country: "Bhutan", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["16", "17", "77"], example: "1712 3456" },
|
||||
{ iso2: "MV", code: "+960", label: "🇲🇻 +960", country: "Maldives", currency: "USD", minLength: 7, maxLength: 7, placeholder: "7-digit mobile number", validPrefixes: ["7", "9"], example: "791 2345" },
|
||||
|
||||
// North America
|
||||
{ iso2: "US", code: "+1", label: "🇺🇸 +1", country: "United States", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit phone number", example: "202 555 0123" },
|
||||
{ iso2: "CA", code: "+1", label: "🇨🇦 +1", country: "Canada", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit phone number", example: "416 555 0123" },
|
||||
{ iso2: "MX", code: "+52", label: "🇲🇽 +52", country: "Mexico", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", example: "55 1234 5678" },
|
||||
|
||||
// Europe & UK
|
||||
{ iso2: "GB", code: "+44", label: "🇬🇧 +44", country: "United Kingdom", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", validPrefixes: ["7"], example: "7123 456789" },
|
||||
{ iso2: "DE", code: "+49", label: "🇩🇪 +49", country: "Germany", currency: "EUR", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", validPrefixes: ["15", "16", "17", "1"], example: "151 23456789" },
|
||||
{ iso2: "FR", code: "+33", label: "🇫🇷 +33", country: "France", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["6", "7"], example: "612 345 678" },
|
||||
{ iso2: "IT", code: "+39", label: "🇮🇹 +39", country: "Italy", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["3"], example: "312 345 6789" },
|
||||
{ iso2: "ES", code: "+34", label: "🇪🇸 +34", country: "Spain", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["6", "7"], example: "612 345 678" },
|
||||
{ iso2: "NL", code: "+31", label: "🇳🇱 +31", country: "Netherlands", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["6"], example: "6 12345678" },
|
||||
{ iso2: "CH", code: "+41", label: "🇨🇭 +41", country: "Switzerland", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["7"], example: "78 123 45 67" },
|
||||
{ iso2: "BE", code: "+32", label: "🇧🇪 +32", country: "Belgium", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits", validPrefixes: ["4"], example: "470 12 34 56" },
|
||||
{ iso2: "AT", code: "+43", label: "🇦🇹 +43", country: "Austria", currency: "EUR", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", validPrefixes: ["6"], example: "664 1234567" },
|
||||
{ iso2: "IE", code: "+353", label: "🇮🇪 +353", country: "Ireland", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["8"], example: "83 123 4567" },
|
||||
{ iso2: "SE", code: "+46", label: "🇸🇪 +46", country: "Sweden", currency: "EUR", minLength: 7, maxLength: 10, placeholder: "7 to 10 digits", validPrefixes: ["7"], example: "70 123 45 67" },
|
||||
{ iso2: "NO", code: "+47", label: "🇳🇴 +47", country: "Norway", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["4", "9"], example: "412 34 567" },
|
||||
{ iso2: "DK", code: "+45", label: "🇩🇰 +45", country: "Denmark", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", example: "20 12 34 56" },
|
||||
{ iso2: "FI", code: "+358", label: "🇫🇮 +358", country: "Finland", currency: "EUR", minLength: 7, maxLength: 10, placeholder: "7 to 10 digits", validPrefixes: ["4", "5"], example: "41 234 5678" },
|
||||
{ iso2: "PT", code: "+351", label: "🇵🇹 +351", country: "Portugal", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["9"], example: "912 345 678" },
|
||||
{ iso2: "GR", code: "+30", label: "🇬🇷 +30", country: "Greece", currency: "EUR", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["6"], example: "691 234 5678" },
|
||||
{ iso2: "PL", code: "+48", label: "🇵🇱 +48", country: "Poland", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["4", "5", "6", "7", "8"], example: "512 345 678" },
|
||||
{ iso2: "CZ", code: "+420", label: "🇨🇿 +420", country: "Czech Republic", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["6", "7"], example: "601 123 456" },
|
||||
{ iso2: "HU", code: "+36", label: "🇭🇺 +36", country: "Hungary", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["20", "30", "31", "50", "70"], example: "20 123 4567" },
|
||||
{ iso2: "RO", code: "+40", label: "🇷🇴 +40", country: "Romania", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["7"], example: "712 345 678" },
|
||||
{ iso2: "UA", code: "+380", label: "🇺🇦 +380", country: "Ukraine", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["5", "6", "7", "9"], example: "50 123 4567" },
|
||||
{ iso2: "IS", code: "+354", label: "🇮🇸 +354", country: "Iceland", currency: "EUR", minLength: 7, maxLength: 9, placeholder: "7 to 9 digits", validPrefixes: ["6", "7", "8"], example: "612 3456" },
|
||||
{ iso2: "LU", code: "+352", label: "🇱🇺 +352", country: "Luxembourg", currency: "EUR", minLength: 8, maxLength: 10, placeholder: "8 to 10 digits", validPrefixes: ["6"], example: "621 123 456" },
|
||||
{ iso2: "HR", code: "+385", label: "🇭🇷 +385", country: "Croatia", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits", validPrefixes: ["9"], example: "91 234 5678" },
|
||||
{ iso2: "SK", code: "+421", label: "🇸🇰 +421", country: "Slovakia", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["9"], example: "912 345 678" },
|
||||
{ iso2: "BG", code: "+359", label: "🇧🇬 +359", country: "Bulgaria", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits", validPrefixes: ["8", "9"], example: "87 123 4567" },
|
||||
{ iso2: "CY", code: "+357", label: "🇨🇾 +357", country: "Cyprus", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit phone number", validPrefixes: ["9"], example: "96 123456" },
|
||||
{ iso2: "EE", code: "+372", label: "🇪🇪 +372", country: "Estonia", currency: "EUR", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits", validPrefixes: ["5"], example: "512 3456" },
|
||||
{ iso2: "LV", code: "+371", label: "🇱🇻 +371", country: "Latvia", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit phone number", validPrefixes: ["2"], example: "2123 4567" },
|
||||
{ iso2: "LT", code: "+370", label: "🇱🇹 +370", country: "Lithuania", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit phone number", validPrefixes: ["6"], example: "612 34567" },
|
||||
{ iso2: "MT", code: "+356", label: "🇲🇹 +356", country: "Malta", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit phone number", validPrefixes: ["7", "9"], example: "7912 3456" },
|
||||
{ iso2: "SI", code: "+386", label: "🇸🇮 +386", country: "Slovenia", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit phone number", validPrefixes: ["3", "4", "5", "6", "7"], example: "31 234 567" },
|
||||
{ iso2: "RU", code: "+7", label: "🇷🇺 +7", country: "Russia", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["9"], example: "912 345-67-89" },
|
||||
{ iso2: "TR", code: "+90", label: "🇹🇷 +90", country: "Turkey", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["5"], example: "501 234 56 78" },
|
||||
|
||||
// Asia-Pacific
|
||||
{ iso2: "AU", code: "+61", label: "🇦🇺 +61", country: "Australia", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["4"], example: "412 345 678" },
|
||||
{ iso2: "NZ", code: "+64", label: "🇳🇿 +64", country: "New Zealand", currency: "USD", minLength: 8, maxLength: 10, placeholder: "8 to 10 digits", validPrefixes: ["2"], example: "21 123 4567" },
|
||||
{ iso2: "JP", code: "+81", label: "🇯🇵 +81", country: "Japan", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", validPrefixes: ["70", "80", "90", "7", "8", "9"], example: "90 1234 5678" },
|
||||
{ iso2: "CN", code: "+86", label: "🇨🇳 +86", country: "China", currency: "USD", minLength: 11, maxLength: 11, placeholder: "11-digit mobile number", validPrefixes: ["1"], example: "138 0013 8000" },
|
||||
{ iso2: "KR", code: "+82", label: "🇰🇷 +82", country: "South Korea", currency: "USD", minLength: 9, maxLength: 11, placeholder: "9 to 11 digits", validPrefixes: ["10", "1"], example: "10 1234 5678" },
|
||||
{ iso2: "HK", code: "+852", label: "🇭🇰 +852", country: "Hong Kong", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["4", "5", "6", "7", "8", "9"], example: "5123 4567" },
|
||||
{ iso2: "TW", code: "+886", label: "🇹🇼 +886", country: "Taiwan", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["9"], example: "912 345 678" },
|
||||
{ iso2: "SG", code: "+65", label: "🇸🇬 +65", country: "Singapore", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["8", "9"], example: "8123 4567" },
|
||||
{ iso2: "MY", code: "+60", label: "🇲🇾 +60", country: "Malaysia", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["1"], example: "12 345 6789" },
|
||||
{ iso2: "ID", code: "+62", label: "🇮🇩 +62", country: "Indonesia", currency: "USD", minLength: 9, maxLength: 12, placeholder: "9 to 12 digits", validPrefixes: ["8"], example: "812 3456 7890" },
|
||||
{ iso2: "PH", code: "+63", label: "🇵🇭 +63", country: "Philippines", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["9"], example: "917 123 4567" },
|
||||
{ iso2: "TH", code: "+66", label: "🇹🇭 +66", country: "Thailand", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["6", "8", "9"], example: "81 234 5678" },
|
||||
{ iso2: "VN", code: "+84", label: "🇻🇳 +84", country: "Vietnam", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["3", "5", "7", "8", "9"], example: "91 234 5678" },
|
||||
|
||||
// Middle East
|
||||
{ iso2: "AE", code: "+971", label: "🇦🇪 +971", country: "UAE", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["5"], example: "50 123 4567" },
|
||||
{ iso2: "SA", code: "+966", label: "🇸🇦 +966", country: "Saudi Arabia", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["5"], example: "50 123 4567" },
|
||||
{ iso2: "QA", code: "+974", label: "🇶🇦 +974", country: "Qatar", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["3", "5", "6", "7"], example: "3312 3456" },
|
||||
{ iso2: "KW", code: "+965", label: "🇰🇼 +965", country: "Kuwait", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["5", "6", "9"], example: "5123 4567" },
|
||||
{ iso2: "OM", code: "+968", label: "🇴🇲 +968", country: "Oman", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["7", "9"], example: "9123 4567" },
|
||||
{ iso2: "BH", code: "+973", label: "🇧🇭 +973", country: "Bahrain", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number", validPrefixes: ["3", "6"], example: "3600 1234" },
|
||||
{ iso2: "IL", code: "+972", label: "🇮🇱 +972", country: "Israel", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["5"], example: "50 234 5678" },
|
||||
{ iso2: "JO", code: "+962", label: "🇯🇴 +962", country: "Jordan", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["7"], example: "7 9012 3456" },
|
||||
{ iso2: "LB", code: "+961", label: "🇱🇧 +961", country: "Lebanon", currency: "USD", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits", validPrefixes: ["3", "7", "8"], example: "70 123 456" },
|
||||
|
||||
// Latin America
|
||||
{ iso2: "BR", code: "+55", label: "🇧🇷 +55", country: "Brazil", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", example: "11 96123 4567" },
|
||||
{ iso2: "AR", code: "+54", label: "🇦🇷 +54", country: "Argentina", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", validPrefixes: ["9"], example: "9 11 1234-5678" },
|
||||
{ iso2: "CL", code: "+56", label: "🇨🇱 +56", country: "Chile", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["9"], example: "9 6123 4567" },
|
||||
{ iso2: "CO", code: "+57", label: "🇨🇴 +57", country: "Colombia", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["3"], example: "300 123 4567" },
|
||||
{ iso2: "PE", code: "+51", label: "🇵🇪 +51", country: "Peru", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["9"], example: "912 345 678" },
|
||||
|
||||
// Africa
|
||||
{ iso2: "ZA", code: "+27", label: "🇿🇦 +27", country: "South Africa", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits", validPrefixes: ["6", "7", "8"], example: "71 234 5678" },
|
||||
{ iso2: "NG", code: "+234", label: "🇳🇬 +234", country: "Nigeria", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits", validPrefixes: ["7", "8", "9"], example: "802 123 4567" },
|
||||
{ iso2: "KE", code: "+254", label: "🇰🇪 +254", country: "Kenya", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["7", "1"], example: "712 345678" },
|
||||
{ iso2: "GH", code: "+233", label: "🇬🇭 +233", country: "Ghana", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["2", "5"], example: "24 123 4567" },
|
||||
{ iso2: "EG", code: "+20", label: "🇪🇬 +20", country: "Egypt", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number", validPrefixes: ["1"], example: "10 1234 5678" },
|
||||
{ iso2: "MA", code: "+212", label: "🇲🇦 +212", country: "Morocco", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number", validPrefixes: ["6", "7"], example: "612-345678" },
|
||||
{ iso2: "MU", code: "+230", label: "🇲🇺 +230", country: "Mauritius", currency: "USD", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits", validPrefixes: ["5"], example: "5251 2345" },
|
||||
];
|
||||
...allCountries.filter(isPrimaryForCallingCode),
|
||||
...allCountries.filter((iso) => !isPrimaryForCallingCode(iso)),
|
||||
].map(buildCountryRule);
|
||||
|
||||
export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b) =>
|
||||
a.country.localeCompare(b.country)
|
||||
);
|
||||
|
||||
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
|
||||
export const DEFAULT_COUNTRY: CountryCode =
|
||||
COUNTRY_CODES.find((c) => c.iso2 === "IN") ?? COUNTRY_CODES[0];
|
||||
|
||||
export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
|
||||
if (!iso) return DEFAULT_COUNTRY;
|
||||
const upper = iso.toUpperCase().trim();
|
||||
const upper = iso.trim().toUpperCase();
|
||||
return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY;
|
||||
};
|
||||
|
||||
export const getCountryRuleByName = (countryName?: string | null): CountryCode => {
|
||||
if (!countryName) return DEFAULT_COUNTRY;
|
||||
const normalized = countryName.toLowerCase().trim();
|
||||
const stripped = countryName.replace(/\s*\(\+\d+\)\s*$/, "").trim().toLowerCase();
|
||||
if (!stripped) return DEFAULT_COUNTRY;
|
||||
|
||||
return (
|
||||
COUNTRY_CODES.find(
|
||||
(c) =>
|
||||
c.country.toLowerCase() === normalized ||
|
||||
c.iso2.toLowerCase() === normalized ||
|
||||
normalized.includes(c.country.toLowerCase())
|
||||
) || {
|
||||
iso2: "IN",
|
||||
code: "+91",
|
||||
label: "🇮🇳 +91",
|
||||
country: countryName,
|
||||
currency: normalized === "india" ? "INR" : "USD",
|
||||
minLength: 7,
|
||||
maxLength: 15,
|
||||
placeholder: "Phone number",
|
||||
}
|
||||
c.country.toLowerCase() === stripped ||
|
||||
c.iso2.toLowerCase() === stripped
|
||||
) ||
|
||||
COUNTRY_CODES.find(
|
||||
(c) =>
|
||||
c.country.toLowerCase().startsWith(stripped) ||
|
||||
stripped.startsWith(c.country.toLowerCase())
|
||||
) ||
|
||||
DEFAULT_COUNTRY
|
||||
);
|
||||
};
|
||||
|
||||
export const getCountryRuleByDialCode = (dialCode?: string | null, countryHint?: string | null): CountryCode => {
|
||||
export const getCountryRuleByDialCode = (
|
||||
dialCode?: string | null,
|
||||
countryHint?: string | null
|
||||
): CountryCode => {
|
||||
if (!dialCode) return DEFAULT_COUNTRY;
|
||||
const normalizedDial = dialCode.startsWith("+") ? dialCode : `+${dialCode}`;
|
||||
|
||||
if (countryHint) {
|
||||
const byCountry = getCountryRuleByName(countryHint);
|
||||
if (byCountry && byCountry.code === dialCode) {
|
||||
return byCountry;
|
||||
}
|
||||
if (byCountry.code === normalizedDial) return byCountry;
|
||||
}
|
||||
|
||||
return (
|
||||
COUNTRY_CODES.find((c) => c.code === dialCode) || {
|
||||
iso2: "IN",
|
||||
code: dialCode,
|
||||
label: dialCode,
|
||||
country: countryHint || "Other",
|
||||
currency: "USD",
|
||||
minLength: 7,
|
||||
maxLength: 15,
|
||||
placeholder: "Phone number",
|
||||
}
|
||||
COUNTRY_CODES.find((c) => c.code === normalizedDial) || DEFAULT_COUNTRY
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Formats a list of prefixes into human-readable text:
|
||||
* e.g. ['3'] -> "3"
|
||||
* e.g. ['6', '7'] -> "6 or 7"
|
||||
* e.g. ['6', '7', '8', '9'] -> "6, 7, 8, or 9"
|
||||
*/
|
||||
export const formatPrefixList = (prefixes: string[]): string => {
|
||||
if (prefixes.length === 0) return "";
|
||||
if (prefixes.length === 1) return prefixes[0];
|
||||
if (prefixes.length === 2) return `${prefixes[0]} or ${prefixes[1]}`;
|
||||
return `${prefixes.slice(0, -1).join(", ")}, or ${prefixes[prefixes.length - 1]}`;
|
||||
const extractNationalDigits = (
|
||||
cleaned: string,
|
||||
digitsOnly: string,
|
||||
rule: CountryCode
|
||||
): string => {
|
||||
const dialDigits = rule.code.replace(/\D/g, "");
|
||||
// Try parsing as a national/international number directly for this country first.
|
||||
const direct = parsePhoneNumberFromString(cleaned, rule.iso2);
|
||||
if (direct?.nationalNumber && (!direct.country || direct.country === rule.iso2)) {
|
||||
return direct.nationalNumber;
|
||||
}
|
||||
if (
|
||||
digitsOnly.startsWith(dialDigits) &&
|
||||
digitsOnly.length > dialDigits.length + 4
|
||||
) {
|
||||
return digitsOnly.slice(dialDigits.length);
|
||||
}
|
||||
return digitsOnly;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates mobile phone number according to country telecom numbering plans.
|
||||
* Enforces digit length, generic starting-prefix rules, and libphonenumber-js mobile validation.
|
||||
* Validates a mobile phone number generically against the selected country's
|
||||
* libphonenumber-js rules, lengths, and number type.
|
||||
* Returns null if valid, or a descriptive user-friendly error message.
|
||||
*/
|
||||
export const validatePhoneNumber = (
|
||||
val?: string | null,
|
||||
value: string,
|
||||
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.";
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return "Mobile number is required";
|
||||
}
|
||||
|
||||
// Strictly disallow hyphens, dashes, and invalid symbols
|
||||
if (/[\-_()/[\]]/.test(trimmed)) {
|
||||
return "Phone number cannot contain hyphens or special symbols.";
|
||||
if (!/^\+?[\d\s\-()]+$/.test(trimmed)) {
|
||||
return "Mobile number can only contain digits";
|
||||
}
|
||||
|
||||
// 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 rule = country
|
||||
? getCountryRuleByName(country)
|
||||
: dialCode
|
||||
? getCountryRuleByDialCode(dialCode, country)
|
||||
: DEFAULT_COUNTRY;
|
||||
|
||||
const cleaned = trimmed.replace(/[\s\-()]/g, "");
|
||||
const digitsOnly = cleaned.replace(/\D/g, "");
|
||||
if (!digitsOnly) {
|
||||
return "Mobile number is required";
|
||||
}
|
||||
|
||||
const allDigits = trimmed.replace(/\D/g, "");
|
||||
if (allDigits.length === 0) {
|
||||
return "Please enter a valid phone number with numeric digits.";
|
||||
const nationalDigits = extractNationalDigits(cleaned, digitsOnly, rule);
|
||||
const lengthLabel =
|
||||
rule.minLength === rule.maxLength
|
||||
? `exactly ${rule.minLength} digits`
|
||||
: `${rule.minLength} to ${rule.maxLength} digits`;
|
||||
|
||||
if (nationalDigits.length < rule.minLength || nationalDigits.length > rule.maxLength) {
|
||||
return `For ${rule.country}, the mobile number must be ${lengthLabel}.`;
|
||||
}
|
||||
|
||||
// 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 candidate = cleaned.startsWith("+") ? cleaned : `${rule.code}${nationalDigits}`;
|
||||
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
|
||||
|
||||
if (!parsed || !parsed.isValid()) {
|
||||
return "Please enter a valid number";
|
||||
}
|
||||
|
||||
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 numberType = parsed.getType();
|
||||
if (numberType && numberType !== "MOBILE" && numberType !== "FIXED_LINE_OR_MOBILE") {
|
||||
return "Please enter a valid number";
|
||||
}
|
||||
|
||||
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 (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 (nationalDigits.length > rule.maxLength || digitsWithoutTrunk0.length > rule.maxLength) {
|
||||
return `${rule.country} mobile number cannot exceed ${rule.maxLength} digits.`;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Generic prefix validation for mobile telecom numbering plans
|
||||
if (rule.validPrefixes && rule.validPrefixes.length > 0) {
|
||||
const hasValidPrefix = rule.validPrefixes.some(
|
||||
(prefix) => digitsWithoutTrunk0.startsWith(prefix) || nationalDigits.startsWith(prefix)
|
||||
);
|
||||
if (!hasValidPrefix) {
|
||||
return `For ${rule.country}, the mobile number must start with ${formatPrefixList(rule.validPrefixes)}.`;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 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} (landlines not allowed).`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const exampleStr = rule.example || rule.placeholder;
|
||||
return `Please enter a valid mobile number for ${rule.country}${exampleStr ? ` (e.g. ${exampleStr})` : ""}.`;
|
||||
return null;
|
||||
};
|
||||
|
||||
export const isValidPhoneNumber = (
|
||||
val?: string | null,
|
||||
val: string,
|
||||
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"
|
||||
fullNumber: string,
|
||||
fallbackCountry?: string
|
||||
): { 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 defaultRule = fallbackCountry
|
||||
? getCountryRuleByName(fallbackCountry)
|
||||
: DEFAULT_COUNTRY;
|
||||
const trimmed = (fullNumber || "").trim();
|
||||
if (!trimmed) {
|
||||
return {
|
||||
country: defaultRule.country,
|
||||
dialCode: defaultRule.code,
|
||||
localDigits: "",
|
||||
iso2: defaultRule.iso2,
|
||||
};
|
||||
}
|
||||
|
||||
const trimmed = fullPhone.trim();
|
||||
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
|
||||
|
||||
if (parsed) {
|
||||
if (parsed && parsed.countryCallingCode) {
|
||||
const matchedRule = parsed.country
|
||||
? getCountryRuleByIso(parsed.country)
|
||||
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
|
||||
|
||||
return {
|
||||
country: matchedRule.country,
|
||||
dialCode: `+${parsed.countryCallingCode}`,
|
||||
dialCode: matchedRule.code,
|
||||
localDigits: parsed.nationalNumber,
|
||||
iso2: matchedRule.iso2,
|
||||
};
|
||||
}
|
||||
|
||||
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
||||
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 cleaned = trimmed.replace(/[\s\-()]/g, "");
|
||||
if (cleaned.startsWith("+")) {
|
||||
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
||||
for (const c of sorted) {
|
||||
if (cleaned.startsWith(c.code)) {
|
||||
return {
|
||||
country: c.country,
|
||||
dialCode: c.code,
|
||||
localDigits: cleaned.slice(c.code.length).replace(/\D/g, ""),
|
||||
iso2: c.iso2,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rawDigits = trimmed.replace(/\D/g, "");
|
||||
return {
|
||||
country: defaultRule.country,
|
||||
dialCode: defaultRule.code,
|
||||
localDigits: rawDigits.slice(0, defaultRule.maxLength),
|
||||
localDigits: cleaned.replace(/\D/g, ""),
|
||||
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}`;
|
||||
export const formatE164Phone = (
|
||||
dialCode: string,
|
||||
localDigits: string,
|
||||
country?: string
|
||||
): string => {
|
||||
const rule = country
|
||||
? getCountryRuleByName(country)
|
||||
: getCountryRuleByDialCode(dialCode, country);
|
||||
const cleaned = (localDigits || "").trim().replace(/[\s\-()]/g, "");
|
||||
if (!cleaned) return "";
|
||||
|
||||
const digits = cleaned.replace(/\D/g, "");
|
||||
const nationalDigits = extractNationalDigits(cleaned, digits, rule);
|
||||
const candidate = cleaned.startsWith("+") ? cleaned : `${rule.code}${nationalDigits}`;
|
||||
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
|
||||
if (parsed && parsed.isValid()) {
|
||||
return parsed.format("E.164");
|
||||
if (parsed) {
|
||||
return parsed.number;
|
||||
}
|
||||
|
||||
let cleanLocal = rawDigits;
|
||||
if (rule.iso2 !== "IT" && cleanLocal.startsWith("0")) {
|
||||
cleanLocal = cleanLocal.replace(/^0+/, "");
|
||||
return nationalDigits ? `${rule.code}${nationalDigits}` : "";
|
||||
};
|
||||
|
||||
export const cleanPhoneInput = (text: string, maxLength = 15): string => {
|
||||
if (!text) return "";
|
||||
const trimmed = text.trim();
|
||||
if (trimmed.startsWith("+")) {
|
||||
const digitsOnly = trimmed.slice(1).replace(/\D/g, "");
|
||||
return `+${digitsOnly}`.slice(0, maxLength + 1);
|
||||
}
|
||||
|
||||
return `${code}${cleanLocal}`;
|
||||
return trimmed.replace(/\D/g, "").slice(0, maxLength);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 = 16, 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;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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,
|
||||
currentValue: string,
|
||||
oldCountry: string,
|
||||
newCountry: string
|
||||
): string => {
|
||||
const trimmed = currentPhone.trim();
|
||||
if (!trimmed) return "";
|
||||
|
||||
const trimmed = (currentValue || "").trim();
|
||||
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} `;
|
||||
if (!parsed.localDigits) return "";
|
||||
|
||||
return formatE164Phone(newRule.code, parsed.localDigits, newRule.country);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
|
||||
|
||||
export const validateEmail = (email?: string | null): string | null => {
|
||||
if (!email || !email.trim()) {
|
||||
export const validateEmail = (value: string): string | null => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return "Email is required";
|
||||
}
|
||||
if (!EMAIL_REGEX.test(email.trim())) {
|
||||
if (trimmed.includes(" ")) {
|
||||
return "Email cannot contain spaces";
|
||||
}
|
||||
if (!EMAIL_REGEX.test(trimmed)) {
|
||||
return "Please enter a valid email address";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const isValidEmail = (email?: string | null): boolean => {
|
||||
return validateEmail(email) === null;
|
||||
export const isValidEmail = (val: string): boolean => {
|
||||
return validateEmail(val) === null;
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in New Issue