Compare commits

..

2 Commits

4 changed files with 69 additions and 31 deletions

View File

@ -357,6 +357,7 @@ export default function App() {
setProfileError(null); setProfileError(null);
setProfileSuccess(false); setProfileSuccess(false);
let cleanedPhoneToSave: string | null = null;
if (profilePhone && profilePhone.trim()) { if (profilePhone && profilePhone.trim()) {
const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry);
if (phoneError) { if (phoneError) {
@ -364,12 +365,13 @@ export default function App() {
setProfileSaving(false); setProfileSaving(false);
return; return;
} }
cleanedPhoneToSave = cleanPhoneInput(profilePhone.trim(), 16, true);
} }
try { try {
await axios.put(`${API_BASE}/api/auth/profile`, { await axios.put(`${API_BASE}/api/auth/profile`, {
full_name: profileDisplayName, full_name: profileDisplayName,
phone_number: profilePhone, phone_number: cleanedPhoneToSave,
country: profileCountry, country: profileCountry,
}, { }, {
headers: { 'Authorization': `Bearer ${userToken}` } headers: { 'Authorization': `Bearer ${userToken}` }
@ -418,6 +420,7 @@ export default function App() {
return; return;
} }
let fullPhone: string | undefined = undefined;
if (authMode === 'register' && authPhone && authPhone.trim()) { if (authMode === 'register' && authPhone && authPhone.trim()) {
const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry);
if (phoneError) { if (phoneError) {
@ -425,6 +428,8 @@ export default function App() {
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
const rawDigits = authPhone.replace(/\D/g, '');
fullPhone = `${authDialCode}${rawDigits}`;
} }
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register'; 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' const payload = authMode === 'login'
? { email: trimmedEmail, password: authPassword } ? { email: trimmedEmail, password: authPassword }
: { : {
@ -804,7 +808,7 @@ export default function App() {
setCheckoutLoading(false); setCheckoutLoading(false);
return; return;
} }
const cleanedPhone = cleanPhoneInput(inputPhone); const cleanedPhone = cleanPhoneInput(inputPhone, 16, true);
const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India'); const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India');
if (phoneError) { if (phoneError) {
alert(phoneError); alert(phoneError);
@ -818,7 +822,7 @@ export default function App() {
headers: { 'Authorization': `Bearer ${userToken}` } headers: { 'Authorization': `Bearer ${userToken}` }
}); });
if (res.data.status === 'success') { if (res.data.status === 'success') {
loggedInUser.phone_number = inputPhone; loggedInUser.phone_number = cleanedPhone;
setLoggedInUser({ ...loggedInUser }); setLoggedInUser({ ...loggedInUser });
} }
} catch (err: any) { } catch (err: any) {
@ -1004,21 +1008,31 @@ export default function App() {
loadingPricing={loadingPricing} loadingPricing={loadingPricing}
loggedInUser={loggedInUser} loggedInUser={loggedInUser}
onUpdateBillingPhone={async () => { onUpdateBillingPhone={async () => {
const newPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || ''); const inputPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || '');
if (newPhone !== null && loggedInUser) { if (inputPhone === null || !loggedInUser) return;
try { const trimmed = inputPhone.trim();
const res = await axios.put(`${API_BASE}/api/auth/profile`, { if (!trimmed) {
phone_number: newPhone alert("A billing phone number is required.");
}, { return;
headers: { 'Authorization': `Bearer ${userToken}` } }
}); const cleanedPhone = cleanPhoneInput(trimmed, 16, true);
if (res.data.status === 'success') { const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser.country || 'India');
setLoggedInUser({ ...loggedInUser, phone_number: newPhone }); if (phoneError) {
alert('Phone number updated successfully for billing!'); alert(phoneError);
} return;
} catch (err: any) { }
alert(err.response?.data?.detail || 'Failed to update phone number.'); 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} verificationResult={verificationResult}

View File

@ -312,7 +312,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<input <input
type="tel" type="tel"
value={authPhone} value={authPhone}
onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength, false))}
placeholder={activeRule.placeholder} placeholder={activeRule.placeholder}
maxLength={activeRule.maxLength} 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" 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"

View File

@ -146,11 +146,11 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-xs font-bold text-slate-500">Phone Number</label> <label className="text-xs font-bold text-slate-500">Phone Number</label>
<input <input
type="text" type="tel"
value={profilePhone} value={profilePhone}
onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, 16, true))}
placeholder={activeRule.placeholder} 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" 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"
/> />
<p className="text-[10px] text-slate-400 font-medium"> <p className="text-[10px] text-slate-400 font-medium">

View File

@ -3,10 +3,11 @@ import { getCountryRuleByDialCode, getCountryRuleByName } from '../constants/cou
/** /**
* Strips non-numeric / non-phone characters from text in real-time * Strips non-numeric / non-phone characters from text in real-time
* If maxLength is provided, strictly restricts digit length * 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 trimmedStart = text.trimStart();
const hasPlus = trimmedStart.startsWith('+'); const hasPlus = allowPlus && trimmedStart.startsWith('+');
const rest = hasPlus ? trimmedStart.slice(1) : text; const rest = hasPlus ? trimmedStart.slice(1) : text;
const digitsOnly = rest.replace(/\D/g, ''); const digitsOnly = rest.replace(/\D/g, '');
const boundedDigits = maxLength ? digitsOnly.slice(0, maxLength) : digitsOnly; 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) * Validates phone number according to country rules (e.g. India = exactly 10 digits)
* Strictly disallows alphabetic characters and invalid symbols
*/ */
export const validatePhoneNumber = ( export const validatePhoneNumber = (
val?: string | null, val?: string | null,
@ -23,9 +25,19 @@ export const validatePhoneNumber = (
): string | null => { ): string | null => {
if (!val || !val.trim()) return null; if (!val || !val.trim()) return null;
const trimmed = val.trim(); 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.'; return 'Please enter a valid phone number with numeric digits.';
} }
@ -42,15 +54,27 @@ export const validatePhoneNumber = (
} }
if (rule && rule.country !== 'Other') { 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 (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.`; return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
} }
} else { } else {
if (digits.length < rule.minLength) { if (localDigits.length < rule.minLength) {
return `${rule.country} phone number must be at least ${rule.minLength} digits.`; 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.`; return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`;
} }
} }
@ -58,10 +82,10 @@ export const validatePhoneNumber = (
} }
// General fallback ITU E.164 // General fallback ITU E.164
if (digits.length < 6) { if (allDigits.length < 6) {
return 'Phone number must contain at least 6 digits.'; 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 'Phone number cannot exceed 15 digits.';
} }
return null; return null;