From 947ca339e554732426b4d2dda419a075aa34d436 Mon Sep 17 00:00:00 2001 From: Urvish Date: Wed, 11 Nov 2026 15:19:13 +0530 Subject: [PATCH] fix(auth): enforce strict national phone length and prevent country code combining in mobile app --- src/constants/countries.ts | 94 +++++++++++++++++-- src/features/auth/components/SignUpForm.tsx | 31 ++++++ .../profile/components/EditProfileForm.tsx | 45 ++------- 3 files changed, 126 insertions(+), 44 deletions(-) diff --git a/src/constants/countries.ts b/src/constants/countries.ts index 7b227e6..982d02e 100644 --- a/src/constants/countries.ts +++ b/src/constants/countries.ts @@ -164,6 +164,11 @@ export const validatePhoneNumber = ( if ((!rule || rule.country === "Other") && country) { rule = getCountryRuleByName(country); } + // If still not found and input starts with '+', match from COUNTRY_CODES + if (!rule && trimmed.startsWith("+")) { + const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length); + rule = sorted.find((c) => trimmed.startsWith(c.code)); + } if (!rule || rule.country === "Other") { if (dialCode === "+91" || (country && country.toLowerCase() === "india")) { rule = getCountryRuleByDialCode("+91"); @@ -174,12 +179,14 @@ export const validatePhoneNumber = ( 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 - ) { + if (trimmed.startsWith("+")) { + // Input includes country code prefix (e.g. +919876543210 or +9198765432) + // Must strip the dial code to extract the actual local number + if (allDigits.startsWith(dialDigits)) { + localDigits = allDigits.slice(dialDigits.length); + } + } else if (allDigits.length > rule.maxLength && allDigits.startsWith(dialDigits)) { + // Input was formatted with dial digits without '+' and exceeds local maxLength (e.g. 919876543210) localDigits = allDigits.slice(dialDigits.length); } @@ -195,6 +202,14 @@ export const validatePhoneNumber = ( return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`; } } + + // Specific country telecom prefix rules + if (dialDigits === "91" || rule.country === "India") { + if (!/^[6-9]/.test(localDigits)) { + return "India mobile number must begin with 6, 7, 8, or 9."; + } + } + return null; } @@ -216,6 +231,71 @@ export const isValidPhoneNumber = ( 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 } => { + const defaultRule = getCountryRuleByName(fallbackCountry) || getCountryRuleByDialCode("+91"); + if (!fullPhone || !fullPhone.trim()) { + return { country: defaultRule.country, dialCode: defaultRule.code, localDigits: "" }; + } + const trimmed = fullPhone.trim(); + + // Try matching dial code prefixes from longest to shortest + 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), + }; + } + + // If no '+' prefix, check if digits start with fallback country dial digits and exceed national length + const dialDigits = defaultRule.code.replace(/\D/g, ""); + const rawDigits = trimmed.replace(/\D/g, ""); + let local = rawDigits; + if ( + dialDigits && + rawDigits.startsWith(dialDigits) && + rawDigits.length > defaultRule.maxLength + ) { + local = rawDigits.slice(dialDigits.length); + } + return { + country: defaultRule.country, + dialCode: defaultRule.code, + localDigits: local.slice(0, defaultRule.maxLength), + }; +}; + +/** + * Formats full phone number cleanly as E.164 without spaces (+) + */ +export const formatE164Phone = (dialCode: string, localDigits: string): string => { + const digits = localDigits.replace(/\D/g, ""); + const code = dialCode.startsWith("+") ? dialCode : `+${dialCode}`; + return digits ? `${code}${digits}` : ""; +}; + +/** + * 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. @@ -246,7 +326,7 @@ export const updatePhoneDialCode = ( } else { const oldDialDigits = oldRule.code.replace(/\D/g, ""); const rawDigits = trimmed.replace(/\D/g, ""); - if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldDialDigits.length) { + if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldRule.maxLength) { nationalDigits = rawDigits.slice(oldDialDigits.length); } else { nationalDigits = rawDigits; diff --git a/src/features/auth/components/SignUpForm.tsx b/src/features/auth/components/SignUpForm.tsx index cf851be..20ce84d 100644 --- a/src/features/auth/components/SignUpForm.tsx +++ b/src/features/auth/components/SignUpForm.tsx @@ -65,6 +65,37 @@ export default function SignUpForm() { }, [countrySearch]); const handlePhoneChange = (text: string) => { + const trimmed = text.trim(); + + // Check if user pasted an international number with '+' prefix + if (trimmed.startsWith("+")) { + const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length); + const matched = sorted.find((c) => trimmed.startsWith(c.code)); + if (matched) { + if (matched.country !== selectedCountry.country) { + setSelectedCountry(matched); + } + const rest = trimmed.slice(matched.code.length).replace(/\D/g, ""); + setPhone(rest.slice(0, matched.maxLength)); + if (phoneError) setPhoneError(""); + return; + } + } + + // Check if user pasted dial digits without '+' (e.g. 919876543210) + const dialDigits = selectedCountry.code.replace(/\D/g, ""); + const rawDigits = trimmed.replace(/\D/g, ""); + if ( + dialDigits && + rawDigits.startsWith(dialDigits) && + rawDigits.length > selectedCountry.maxLength + ) { + const rest = rawDigits.slice(dialDigits.length); + setPhone(rest.slice(0, selectedCountry.maxLength)); + if (phoneError) setPhoneError(""); + return; + } + const digits = text.replace(/\D/g, ""); setPhone(digits.slice(0, selectedCountry.maxLength)); if (phoneError) setPhoneError(""); diff --git a/src/features/profile/components/EditProfileForm.tsx b/src/features/profile/components/EditProfileForm.tsx index 488156d..503626b 100644 --- a/src/features/profile/components/EditProfileForm.tsx +++ b/src/features/profile/components/EditProfileForm.tsx @@ -23,6 +23,10 @@ import { getCountryRuleByName, updatePhoneDialCode, validatePhoneNumber, + isValidPhoneNumber, + parsePhoneNumber, + formatE164Phone, + cleanPhoneInput, } from "@/constants/countries"; interface EditProfileFormProps { @@ -53,34 +57,6 @@ const COMMON_COUNTRIES = [ "Spain", ]; -export const isValidPhoneNumber = (val?: string, country?: string): boolean => { - if (!val || !val.trim()) return true; - return validatePhoneNumber(val, undefined, country) === null; -}; - -const cleanPhoneInput = (text: string, maxLength = 16): string => { - const trimmedStart = text.trimStart(); - const hasPlus = trimmedStart.startsWith("+"); - const rest = hasPlus ? trimmedStart.slice(1) : text; - // Disallow all non-digits except a single separating space after country code - // Specifically strip hyphens, dashes, parentheses, underscores, and letters - const noDashes = rest.replace(/[\-()_a-zA-Z]/g, ""); - const normalized = noDashes.replace(/\s+/g, " "); - let digitCount = 0; - let result = ""; - for (const ch of normalized) { - if (/\d/.test(ch)) { - if (digitCount < maxLength) { - digitCount++; - result += ch; - } - } else if (ch === " " && digitCount > 0 && !result.includes(" ")) { - result += ch; - } - } - return hasPlus ? `+${result}` : result; -}; - export default function EditProfileForm({ initialName = "User Name", initialEmail = "user@example.com", @@ -118,10 +94,10 @@ export default function EditProfileForm({ }; const handlePhoneChange = (text: string) => { - const cleaned = cleanPhoneInput(text); + const cleaned = cleanPhoneInput(text, activeRule.maxLength + activeRule.code.length + 2); setPhone(cleaned); if (phoneError) { - if (!cleaned.trim() || isValidPhoneNumber(cleaned, country)) { + if (!cleaned.trim() || isValidPhoneNumber(cleaned, activeRule.code, country)) { setPhoneError(""); } } @@ -164,13 +140,8 @@ export default function EditProfileForm({ let normalizedPhone = ""; if (trimmedPhone) { const rule = getCountryRuleByName(country); - const digitsOnly = trimmedPhone.replace(/\D/g, ""); - const dialDigits = rule.code.replace(/\D/g, ""); - let localDigits = digitsOnly; - if (digitsOnly.startsWith(dialDigits) && digitsOnly.length > dialDigits.length) { - localDigits = digitsOnly.slice(dialDigits.length); - } - normalizedPhone = `${rule.code}${localDigits}`; + const parsed = parsePhoneNumber(trimmedPhone, country); + normalizedPhone = formatE164Phone(rule.code, parsed.localDigits); } onSave?.(trimmedName, normalizedPhone, country); -- 2.34.1