fix/issue-124-country-mobile-validation #139

Open
shivani wants to merge 3 commits from fix/issue-124-country-mobile-validation into main
4 changed files with 263 additions and 306 deletions

View File

@ -1,408 +1,353 @@
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;
validPrefixes?: string[];
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" },
{ iso2: "PK", code: "+92", label: "🇵🇰 +92", country: "Pakistan", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "BD", code: "+880", label: "🇧🇩 +880", country: "Bangladesh", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "LK", code: "+94", label: "🇱🇰 +94", country: "Sri Lanka", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "NP", code: "+977", label: "🇳🇵 +977", country: "Nepal", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "BT", code: "+975", label: "🇧🇹 +975", country: "Bhutan", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "MV", code: "+960", label: "🇲🇻 +960", country: "Maldives", currency: "USD", minLength: 7, maxLength: 7, placeholder: "7-digit mobile number" },
// North America
{ iso2: "US", code: "+1", label: "🇺🇸 +1", country: "United States", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit phone number" },
{ iso2: "CA", code: "+1", label: "🇨🇦 +1", country: "Canada", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit phone number" },
{ iso2: "MX", code: "+52", label: "🇲🇽 +52", country: "Mexico", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
// Europe & UK
{ iso2: "GB", code: "+44", label: "🇬🇧 +44", country: "United Kingdom", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "DE", code: "+49", label: "🇩🇪 +49", country: "Germany", currency: "EUR", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "FR", code: "+33", label: "🇫🇷 +33", country: "France", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "IT", code: "+39", label: "🇮🇹 +39", country: "Italy", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "ES", code: "+34", label: "🇪🇸 +34", country: "Spain", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "NL", code: "+31", label: "🇳🇱 +31", country: "Netherlands", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "CH", code: "+41", label: "🇨🇭 +41", country: "Switzerland", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "BE", code: "+32", label: "🇧🇪 +32", country: "Belgium", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits" },
{ iso2: "AT", code: "+43", label: "🇦🇹 +43", country: "Austria", currency: "EUR", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "IE", code: "+353", label: "🇮🇪 +353", country: "Ireland", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "SE", code: "+46", label: "🇸🇪 +46", country: "Sweden", currency: "EUR", minLength: 7, maxLength: 10, placeholder: "7 to 10 digits" },
{ iso2: "NO", code: "+47", label: "🇳🇴 +47", country: "Norway", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "DK", code: "+45", label: "🇩🇰 +45", country: "Denmark", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "FI", code: "+358", label: "🇫🇮 +358", country: "Finland", currency: "EUR", minLength: 6, maxLength: 10, placeholder: "6 to 10 digits" },
{ iso2: "PT", code: "+351", label: "🇵🇹 +351", country: "Portugal", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "GR", code: "+30", label: "🇬🇷 +30", country: "Greece", currency: "EUR", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "PL", code: "+48", label: "🇵🇱 +48", country: "Poland", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "CZ", code: "+420", label: "🇨🇿 +420", country: "Czech Republic", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "HU", code: "+36", label: "🇭🇺 +36", country: "Hungary", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "RO", code: "+40", label: "🇷🇴 +40", country: "Romania", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "UA", code: "+380", label: "🇺🇦 +380", country: "Ukraine", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "IS", code: "+354", label: "🇮🇸 +354", country: "Iceland", currency: "EUR", minLength: 7, maxLength: 9, placeholder: "7 to 9 digits" },
{ iso2: "LU", code: "+352", label: "🇱🇺 +352", country: "Luxembourg", currency: "EUR", minLength: 8, maxLength: 10, placeholder: "8 to 10 digits" },
{ iso2: "HR", code: "+385", label: "🇭🇷 +385", country: "Croatia", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits" },
{ iso2: "SK", code: "+421", label: "🇸🇰 +421", country: "Slovakia", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "BG", code: "+359", label: "🇧🇬 +359", country: "Bulgaria", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits" },
{ iso2: "RU", code: "+7", label: "🇷🇺 +7", country: "Russia", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "TR", code: "+90", label: "🇹🇷 +90", country: "Turkey", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
// Asia-Pacific
{ iso2: "AU", code: "+61", label: "🇦🇺 +61", country: "Australia", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "NZ", code: "+64", label: "🇳🇿 +64", country: "New Zealand", currency: "USD", minLength: 8, maxLength: 10, placeholder: "8 to 10 digits" },
{ iso2: "JP", code: "+81", label: "🇯🇵 +81", country: "Japan", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "CN", code: "+86", label: "🇨🇳 +86", country: "China", currency: "USD", minLength: 11, maxLength: 11, placeholder: "11-digit mobile number" },
{ iso2: "KR", code: "+82", label: "🇰🇷 +82", country: "South Korea", currency: "USD", minLength: 9, maxLength: 11, placeholder: "9 to 11 digits" },
{ iso2: "HK", code: "+852", label: "🇭🇰 +852", country: "Hong Kong", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "TW", code: "+886", label: "🇹🇼 +886", country: "Taiwan", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "SG", code: "+65", label: "🇸🇬 +65", country: "Singapore", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "MY", code: "+60", label: "🇲🇾 +60", country: "Malaysia", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "ID", code: "+62", label: "🇮🇩 +62", country: "Indonesia", currency: "USD", minLength: 9, maxLength: 12, placeholder: "9 to 12 digits" },
{ iso2: "PH", code: "+63", label: "🇵🇭 +63", country: "Philippines", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "TH", code: "+66", label: "🇹🇭 +66", country: "Thailand", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "VN", code: "+84", label: "🇻🇳 +84", country: "Vietnam", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
// Middle East
{ iso2: "AE", code: "+971", label: "🇦🇪 +971", country: "UAE", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "SA", code: "+966", label: "🇸🇦 +966", country: "Saudi Arabia", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "QA", code: "+974", label: "🇶🇦 +974", country: "Qatar", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "KW", code: "+965", label: "🇰🇼 +965", country: "Kuwait", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "OM", code: "+968", label: "🇴🇲 +968", country: "Oman", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "BH", code: "+973", label: "🇧🇭 +973", country: "Bahrain", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "IL", code: "+972", label: "🇮🇱 +972", country: "Israel", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "JO", code: "+962", label: "🇯🇴 +962", country: "Jordan", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "LB", code: "+961", label: "🇱🇧 +961", country: "Lebanon", currency: "USD", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits" },
// Latin America
{ iso2: "BR", code: "+55", label: "🇧🇷 +55", country: "Brazil", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "AR", code: "+54", label: "🇦🇷 +54", country: "Argentina", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "CL", code: "+56", label: "🇨🇱 +56", country: "Chile", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "CO", code: "+57", label: "🇨🇴 +57", country: "Colombia", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "PE", code: "+51", label: "🇵🇪 +51", country: "Peru", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
// Africa
{ iso2: "ZA", code: "+27", label: "🇿🇦 +27", country: "South Africa", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "NG", code: "+234", label: "🇳🇬 +234", country: "Nigeria", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "KE", code: "+254", label: "🇰🇪 +254", country: "Kenya", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "GH", code: "+233", label: "🇬🇭 +233", country: "Ghana", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "EG", code: "+20", label: "🇪🇬 +20", country: "Egypt", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "MA", code: "+212", label: "🇲🇦 +212", country: "Morocco", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "MU", code: "+230", label: "🇲🇺 +230", country: "Mauritius", currency: "USD", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits" },
];
...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
);
};
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.
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07).
* 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}.`;
}
let rule = country ? getCountryRuleByName(country) : undefined;
if (!rule && 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 (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}).`;
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;
};

View File

@ -20,27 +20,31 @@ interface LoginTabsProps {
}
export default function LoginTabs({
activeTab,
onTabChange,
activeTab: _activeTab,
onTabChange: _onTabChange,
}: LoginTabsProps) {
// Temporarily hidden: restore return JSX below (and Phone tab inside) when multi-tab login is re-enabled
return null;
/*
return (
<View style={styles.container}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Login with Email"
style={styles.tab}
onPress={() => onTabChange("email")}
onPress={() => _onTabChange("email")}
>
<Text
style={[
styles.text,
activeTab === "email" && styles.activeText,
_activeTab === "email" && styles.activeText,
]}
>
Email
</Text>
{activeTab === "email" && (
{_activeTab === "email" && (
<View style={styles.indicator} />
)}
</Pressable>
@ -49,23 +53,24 @@ export default function LoginTabs({
accessibilityRole="button"
accessibilityLabel="Login with Phone"
style={styles.tab}
onPress={() => onTabChange("phone")}
onPress={() => _onTabChange("phone")}
>
<Text
style={[
styles.text,
activeTab === "phone" && styles.activeText,
_activeTab === "phone" && styles.activeText,
]}
>
Phone
</Text>
{activeTab === "phone" && (
{_activeTab === "phone" && (
<View style={styles.indicator} />
)}
</Pressable>
</View>
);
*/
}
const styles = StyleSheet.create({

View File

@ -261,7 +261,11 @@ export default function SignUpForm() {
<TextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder={selectedCountry.placeholder || "Phone Number (Optional)"}
placeholder={
selectedCountry.example
? `e.g. ${selectedCountry.example}`
: selectedCountry.placeholder || "Phone Number (Optional)"
}
placeholderTextColor={AuthColors.textSecondary}
keyboardType="number-pad"
autoCapitalize="none"

View File

@ -24,7 +24,6 @@ import {
SORTED_COUNTRY_CODES,
getCountryRuleByName,
validatePhoneNumber,
isValidPhoneNumber,
parsePhoneNumber,
formatE164Phone,
cleanPhoneInput,
@ -91,9 +90,7 @@ export default function EditProfileForm({
const cleaned = cleanPhoneInput(text, activeRule.maxLength + activeRule.code.length + 2);
setPhone(cleaned);
if (phoneError) {
if (!cleaned.trim() || isValidPhoneNumber(cleaned, activeRule.code, country)) {
setPhoneError("");
}
setPhoneError("");
}
};
@ -175,7 +172,13 @@ export default function EditProfileForm({
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`}
placeholder={
activeRule.example
? `e.g. ${activeRule.code} ${activeRule.example}`
: activeRule.placeholder
? `e.g. ${activeRule.code} ${activeRule.placeholder}`
: `e.g. ${activeRule.code} 9876543210`
}
keyboardType="phone-pad"
maxLength={activeRule.maxLength + activeRule.code.length + 2}
textContentType="telephoneNumber"