diff --git a/src/App.tsx b/src/App.tsx index ad43070..a5c5d6b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -357,6 +357,7 @@ export default function App() { setProfileError(null); setProfileSuccess(false); + let cleanedPhoneToSave: string | null = null; if (profilePhone && profilePhone.trim()) { const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); if (phoneError) { @@ -364,12 +365,13 @@ export default function App() { setProfileSaving(false); return; } + cleanedPhoneToSave = cleanPhoneInput(profilePhone.trim(), 16, true); } try { await axios.put(`${API_BASE}/api/auth/profile`, { full_name: profileDisplayName, - phone_number: profilePhone, + phone_number: cleanedPhoneToSave, country: profileCountry, }, { headers: { 'Authorization': `Bearer ${userToken}` } @@ -418,6 +420,7 @@ export default function App() { return; } + let fullPhone: string | undefined = undefined; if (authMode === 'register' && authPhone && authPhone.trim()) { const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); if (phoneError) { @@ -425,6 +428,8 @@ export default function App() { setAuthLoading(false); return; } + const rawDigits = authPhone.replace(/\D/g, ''); + fullPhone = `${authDialCode}${rawDigits}`; } const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register'; @@ -438,7 +443,6 @@ export default function App() { } } - const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined; const payload = authMode === 'login' ? { email: trimmedEmail, password: authPassword } : { @@ -804,7 +808,7 @@ export default function App() { setCheckoutLoading(false); return; } - const cleanedPhone = cleanPhoneInput(inputPhone); + const cleanedPhone = cleanPhoneInput(inputPhone, 16, true); const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India'); if (phoneError) { alert(phoneError); @@ -818,7 +822,7 @@ export default function App() { headers: { 'Authorization': `Bearer ${userToken}` } }); if (res.data.status === 'success') { - loggedInUser.phone_number = inputPhone; + loggedInUser.phone_number = cleanedPhone; setLoggedInUser({ ...loggedInUser }); } } catch (err: any) { @@ -1004,21 +1008,31 @@ export default function App() { loadingPricing={loadingPricing} loggedInUser={loggedInUser} onUpdateBillingPhone={async () => { - const newPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || ''); - if (newPhone !== null && loggedInUser) { - try { - const res = await axios.put(`${API_BASE}/api/auth/profile`, { - phone_number: newPhone - }, { - headers: { 'Authorization': `Bearer ${userToken}` } - }); - if (res.data.status === 'success') { - setLoggedInUser({ ...loggedInUser, phone_number: newPhone }); - alert('Phone number updated successfully for billing!'); - } - } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to update phone number.'); + const inputPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || ''); + if (inputPhone === null || !loggedInUser) return; + const trimmed = inputPhone.trim(); + if (!trimmed) { + alert("A billing phone number is required."); + return; + } + const cleanedPhone = cleanPhoneInput(trimmed, 16, true); + const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser.country || 'India'); + if (phoneError) { + alert(phoneError); + return; + } + try { + const res = await axios.put(`${API_BASE}/api/auth/profile`, { + phone_number: cleanedPhone + }, { + headers: { 'Authorization': `Bearer ${userToken}` } + }); + if (res.data.status === 'success') { + setLoggedInUser({ ...loggedInUser, phone_number: cleanedPhone }); + alert('Phone number updated successfully for billing!'); } + } catch (err: any) { + alert(err.response?.data?.detail || 'Failed to update phone number.'); } }} verificationResult={verificationResult} diff --git a/src/components/auth/AuthModal.tsx b/src/components/auth/AuthModal.tsx index 7c8fe9b..330d02d 100644 --- a/src/components/auth/AuthModal.tsx +++ b/src/components/auth/AuthModal.tsx @@ -312,7 +312,7 @@ export const AuthModal: React.FC = ({ setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} + onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength, false))} placeholder={activeRule.placeholder} maxLength={activeRule.maxLength} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 placeholder:text-slate-700" diff --git a/src/components/auth/ProfileDrawer.tsx b/src/components/auth/ProfileDrawer.tsx index 76726c4..27a1c58 100644 --- a/src/components/auth/ProfileDrawer.tsx +++ b/src/components/auth/ProfileDrawer.tsx @@ -146,11 +146,11 @@ export const ProfileDrawer: React.FC = ({
setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} + onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, 16, true))} placeholder={activeRule.placeholder} - maxLength={activeRule.maxLength} + maxLength={16} className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />

diff --git a/src/utils/validation.ts b/src/utils/validation.ts index 7938628..aa90cdc 100644 --- a/src/utils/validation.ts +++ b/src/utils/validation.ts @@ -3,10 +3,11 @@ import { getCountryRuleByDialCode, getCountryRuleByName } from '../constants/cou /** * 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?: number): string => { +export const cleanPhoneInput = (text: string, maxLength?: number, allowPlus = true): string => { const trimmedStart = text.trimStart(); - const hasPlus = trimmedStart.startsWith('+'); + 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; @@ -15,6 +16,7 @@ export const cleanPhoneInput = (text: string, maxLength?: number): string => { /** * 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, @@ -23,9 +25,19 @@ export const validatePhoneNumber = ( ): string | null => { if (!val || !val.trim()) return null; const trimmed = val.trim(); - const digits = trimmed.replace(/\D/g, ''); - if (digits.length === 0) { + // Explicitly disallow alphabetic characters + if (/[a-zA-Z]/.test(trimmed)) { + return 'Phone number cannot contain alphabetic characters.'; + } + + // Strictly enforce numeric digits with optional leading '+' and standard formatting separators + 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.'; } @@ -42,15 +54,27 @@ export const validatePhoneNumber = ( } 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 (digits.length !== rule.minLength) { + if (localDigits.length !== rule.minLength) { return `${rule.country} phone number must be exactly ${rule.minLength} digits.`; } } else { - if (digits.length < rule.minLength) { + if (localDigits.length < rule.minLength) { return `${rule.country} phone number must be at least ${rule.minLength} digits.`; } - if (digits.length > rule.maxLength) { + if (localDigits.length > rule.maxLength) { return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`; } } @@ -58,10 +82,10 @@ export const validatePhoneNumber = ( } // General fallback ITU E.164 - if (digits.length < 6) { + if (allDigits.length < 6) { return 'Phone number must contain at least 6 digits.'; } - if (digits.length > 15) { + if (allDigits.length > 15) { return 'Phone number cannot exceed 15 digits.'; } return null;