Merge main into fix/issue-12-back-navigation-library

This commit is contained in:
ShivaniKhaire 2026-10-07 13:16:36 +05:30
commit 720a9b165c
7 changed files with 395 additions and 81 deletions

View File

@ -2,9 +2,11 @@ import { useState, useEffect } from 'react';
import axios from 'axios';
import { CURRICULUM_MODULES } from './constants/modules';
import { getCountryRuleByName } from './constants/countries';
import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types';
import { API_BASE } from './services/api';
import { loadRazorpayScript } from './services/razorpay';
import { cleanPhoneInput, validatePhoneNumber } from './utils/validation';
// Modular Subcomponents
import { StoreHeader } from './components/layout/StoreHeader';
@ -236,14 +238,12 @@ export default function App() {
calculatePricing();
}, [cart, appliedCoupon, currency]);
// Update currency automatically on country selection during registration
// Update currency and dial code automatically on country selection during registration
useEffect(() => {
if (authMode === 'register') {
if (authCountry === 'India') {
setCurrency('INR');
} else {
setCurrency('USD');
}
const rule = getCountryRuleByName(authCountry);
setCurrency(rule.currency);
setAuthDialCode(rule.code);
}
}, [authCountry, authMode]);
@ -265,11 +265,8 @@ export default function App() {
setProfileDisplayName(profileRes.data.display_name || '');
setProfilePhone(profileRes.data.phone_number || '');
setProfileCountry(profileRes.data.country || 'India');
if (profileRes.data.country === 'India') {
setCurrency('INR');
} else {
setCurrency('USD');
}
const countryRule = getCountryRuleByName(profileRes.data.country || 'India');
setCurrency(countryRule.currency);
} catch (err) {
console.error('Failed to fetch user profile:', err);
handleLogout();
@ -298,6 +295,15 @@ export default function App() {
setProfileError(null);
setProfileSuccess(false);
if (profilePhone && profilePhone.trim()) {
const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry);
if (phoneError) {
setProfileError(phoneError);
setProfileSaving(false);
return;
}
}
try {
await axios.put(`${API_BASE}/api/auth/profile`, {
full_name: profileDisplayName,
@ -323,7 +329,40 @@ export default function App() {
setAuthLoading(true);
setAuthError(null);
if (authMode === 'register' && authPhone && authPhone.trim()) {
const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry);
if (phoneError) {
setAuthError(phoneError);
setAuthLoading(false);
return;
}
}
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
if (authMode === 'register') {
if (authPassword.length < 8) {
setAuthError('Password must be at least 8 characters long.');
setAuthLoading(false);
return;
}
if (!/[A-Z]/.test(authPassword)) {
setAuthError('Password must contain at least one uppercase letter.');
setAuthLoading(false);
return;
}
if (!/[0-9]/.test(authPassword)) {
setAuthError('Password must contain at least one number.');
setAuthLoading(false);
return;
}
if (!/[^A-Za-z0-9\s]/.test(authPassword)) {
setAuthError('Password must contain at least one special character.');
setAuthLoading(false);
return;
}
}
const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined;
const payload = authMode === 'login'
? { email: authEmail, password: authPassword }
@ -377,7 +416,7 @@ export default function App() {
setChangePasswordError('New password must contain at least one number.');
return;
}
if (!/[^A-Za-z0-9]/.test(changeNewPassword)) {
if (!/[^A-Za-z0-9\s]/.test(changeNewPassword)) {
setChangePasswordError('New password must contain at least one special character.');
return;
}
@ -448,7 +487,7 @@ export default function App() {
setAuthLoading(false);
return;
}
if (!/[^A-Za-z0-9]/.test(resetNewPassword)) {
if (!/[^A-Za-z0-9\s]/.test(resetNewPassword)) {
setAuthError('New password must contain at least one special character.');
setAuthLoading(false);
return;
@ -491,9 +530,18 @@ export default function App() {
currency: currency
}, { headers });
setPricingCalc(res.data);
} catch (err) {
const calcData = res.data;
if (appliedCoupon && (!calcData.coupon_applied || calcData.coupon_applied === 'None')) {
calcData.coupon_error = calcData.coupon_error || 'Invalid or expired coupon code.';
}
setPricingCalc(calcData);
} catch (err: any) {
console.error('Pricing engine calculation error:', err);
const errorMsg = err.response?.data?.detail || 'Invalid or expired coupon code.';
setPricingCalc((prev: any) => ({
...(prev || {}),
coupon_error: errorMsg
}));
} finally {
setLoadingPricing(false);
}
@ -550,6 +598,7 @@ export default function App() {
const removePromoCode = () => {
setAppliedCoupon(null);
setCouponCode('');
setPricingCalc((prev: any) => (prev ? { ...prev, coupon_error: null } : null));
};
const isModuleUnlocked = (code: string) => {
@ -599,10 +648,17 @@ export default function App() {
setCheckoutLoading(true);
setVerificationResult(null);
const isCouponValid = Boolean(
pricingCalc &&
pricingCalc.coupon_applied &&
pricingCalc.coupon_applied !== 'None' &&
!pricingCalc.coupon_error
);
try {
const orderRes = await axios.post(`${API_BASE}/api/checkout/create-order`, {
cart_item_codes: cart.map(item => item.code),
coupon_code: appliedCoupon || undefined,
coupon_code: isCouponValid ? appliedCoupon : undefined,
currency: currency
}, {
headers: { 'Authorization': `Bearer ${userToken}` }
@ -629,9 +685,16 @@ export default function App() {
setCheckoutLoading(false);
return;
}
const cleanedPhone = cleanPhoneInput(inputPhone);
const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India');
if (phoneError) {
alert(phoneError);
setCheckoutLoading(false);
return;
}
try {
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
phone_number: inputPhone
phone_number: cleanedPhone
}, {
headers: { 'Authorization': `Bearer ${userToken}` }
});
@ -646,6 +709,9 @@ export default function App() {
}
}
let isPaymentCancelled = false;
let isPaymentCompleted = false;
const rzpOptions = {
key: razorpayKeyId,
amount: Math.round(grand_total * 100),
@ -659,7 +725,25 @@ export default function App() {
email: loggedInUser?.email || '',
contact: loggedInUser?.phone_number || loggedInUser?.phone || ''
},
modal: {
confirm_close: true,
escape: true,
backdropclose: false,
ondismiss: function () {
if (!isPaymentCompleted) {
isPaymentCancelled = true;
setCheckoutLoading(false);
console.log('Razorpay payment modal dismissed / cancelled by user.');
}
}
},
handler: async function (response: any) {
if (isPaymentCancelled) {
console.warn('Payment was cancelled by the user. Verification ignored.');
setCheckoutLoading(false);
return;
}
isPaymentCompleted = true;
setCheckoutLoading(true);
try {
const verifyRes = await axios.post(`${API_BASE}/api/checkout/verify`, {
@ -683,6 +767,7 @@ export default function App() {
message: verifyRes.data.message || 'Payment verified successfully and module entitlements unlocked!'
});
// Push a history state so that pressing browser/device Back button will be intercepted
// by popstate and redirected to All Modules / Library instead of returning to the Subscription page
if (typeof window !== 'undefined') {
@ -691,7 +776,15 @@ export default function App() {
if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) {
setTimeout(() => {
openMobileApp({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined });
if (/Android/i.test(navigator.userAgent)) {
// Use Android Intent format to avoid blocked navigation in Android Chrome
window.location.href = 'intent://#Intent;scheme=acupedia;package=com.anonymous.acupedia;end';
setTimeout(() => {
window.location.href = 'acupedia://';
}, 500);
} else {
window.location.href = 'acupedia://';
}
}, 1500);
}
@ -714,6 +807,7 @@ export default function App() {
const razorpayInstance = new (window as any).Razorpay(rzpOptions);
razorpayInstance.on('payment.failed', function (resp: any) {
setCheckoutLoading(false);
alert(`Payment failed! Reason: ${resp.error.description}`);
});
razorpayInstance.open();

View File

@ -3,7 +3,8 @@ import {
XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw,
Phone, Globe, Eye, EyeOff, LogIn, UserPlus
} from 'lucide-react';
import { COUNTRY_CODES } from '../../constants/countries';
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation';
interface AuthModalProps {
isOpen: boolean;
@ -76,6 +77,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
onResetPasswordSubmit,
}) => {
const [showPassword, setShowPassword] = useState(false);
const activeRule = getCountryRuleByDialCode(authDialCode);
if (!isOpen) return null;
@ -290,7 +292,14 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<div className="relative">
<select
value={authDialCode}
onChange={(e) => setAuthDialCode(e.target.value)}
onChange={(e) => {
const newCode = e.target.value;
setAuthDialCode(newCode);
const rule = getCountryRuleByDialCode(newCode);
if (rule && rule.country !== 'Other') {
setAuthCountry(rule.country);
}
}}
className="w-[90px] bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none"
>
{COUNTRY_CODES.map((cc) => (
@ -303,11 +312,17 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<input
type="tel"
value={authPhone}
onChange={(e) => setAuthPhone(e.target.value)}
placeholder="9876543210"
onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength))}
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"
/>
</div>
<p className="text-[10px] text-slate-500 font-medium">
{activeRule.minLength === activeRule.maxLength
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
</div>
)}
@ -320,14 +335,21 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<div className="relative">
<select
value={authCountry}
onChange={(e) => setAuthCountry(e.target.value)}
onChange={(e) => {
const newCountry = e.target.value;
setAuthCountry(newCountry);
const rule = getCountryRuleByName(newCountry);
if (rule) {
setAuthDialCode(rule.code);
}
}}
className="w-full 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 appearance-none"
>
<option value="India">India (Calculates in INR ₹)</option>
<option value="United States">United States (Calculates in USD $)</option>
<option value="United Kingdom">United Kingdom (Calculates in USD $)</option>
<option value="Germany">Germany (Calculates in USD $)</option>
<option value="Australia">Australia (Calculates in USD $)</option>
{COUNTRY_CODES.map((cc) => (
<option key={cc.code} value={cc.country}>
{cc.country} (Calculates in {cc.currency} {cc.currency === 'INR' ? '₹' : '$'})
</option>
))}
</select>
<div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500 text-xs">
▼

View File

@ -4,6 +4,8 @@ import {
Eye, EyeOff, RefreshCw, LogOut
} from 'lucide-react';
import type { UserProfile, ModuleItem, Currency } from '../../types';
import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation';
interface ProfileDrawerProps {
isOpen: boolean;
@ -70,6 +72,7 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
}) => {
const [showOldPassword, setShowOldPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const activeRule = getCountryRuleByName(profileCountry);
if (!isOpen || !loggedInUser) return null;
@ -143,10 +146,16 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<input
type="text"
value={profilePhone}
onChange={(e) => setProfilePhone(e.target.value)}
placeholder="+919876543210"
onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength))}
placeholder={activeRule.placeholder}
maxLength={activeRule.maxLength}
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">
{activeRule.minLength === activeRule.maxLength
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
</div>
<div className="space-y-1.5">
@ -154,25 +163,18 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<select
value={profileCountry}
onChange={(e) => {
setProfileCountry(e.target.value);
if (e.target.value === 'India') {
setCurrency('INR');
} else {
setCurrency('USD');
}
const newCountry = e.target.value;
setProfileCountry(newCountry);
const rule = getCountryRuleByName(newCountry);
setCurrency(rule.currency);
}}
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"
>
<option value="India">India</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Australia">Australia</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Japan">Japan</option>
<option value="China">China</option>
<option value="Singapore">Singapore</option>
<option value="Canada">Canada</option>
{COUNTRY_CODES.map((cc) => (
<option key={cc.code} value={cc.country}>
{cc.country}
</option>
))}
</select>
</div>
@ -285,7 +287,7 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<span className={/[0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
&bull; 1 number
</span>
<span className={/[^A-Za-z0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
<span className={/[^A-Za-z0-9\s]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
&bull; 1 special char
</span>
</div>

View File

@ -141,9 +141,11 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
</button>
</div>
{appliedCoupon &&
(pricingCalc?.coupon_error ? (
(pricingCalc?.coupon_error || !pricingCalc?.coupon_applied || pricingCalc?.coupon_applied === 'None' ? (
<div className="flex justify-between items-center bg-rose-50 border border-rose-200 text-rose-700 text-xs px-3 py-2 rounded-xl font-bold">
<span className="flex items-center gap-1">⚠️ {pricingCalc.coupon_error}</span>
<span className="flex items-center gap-1">
⚠️ {pricingCalc?.coupon_error || 'Invalid or expired coupon code.'}
</span>
<button
onClick={removePromoCode}
className="text-rose-700 hover:text-rose-900 font-bold ml-2 cursor-pointer"
@ -183,18 +185,44 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
: `$${pricingCalc.base_subtotal}`}
</span>
</div>
{pricingCalc.total_discounts > 0 && (
{pricingCalc.bundle_discount_amount > 0 && (
<div className="flex justify-between text-xs text-emerald-700 font-bold">
<span>Total Discounts</span>
<span>Bundle Discount</span>
<span>
-{currency === 'INR'
? `₹${pricingCalc.total_discounts}`
? `₹${pricingCalc.bundle_discount_amount}`
: currency === 'EUR'
? `€${pricingCalc.total_discounts}`
: `$${pricingCalc.total_discounts}`}
? `€${pricingCalc.bundle_discount_amount}`
: `$${pricingCalc.bundle_discount_amount}`}
</span>
</div>
)}
{pricingCalc.coupon_discount_amount > 0 && (
<div className="flex justify-between text-xs text-emerald-700 font-bold">
<span>Coupon Discount ({appliedCoupon})</span>
<span>
-{currency === 'INR'
? `₹${pricingCalc.coupon_discount_amount}`
: currency === 'EUR'
? `€${pricingCalc.coupon_discount_amount}`
: `$${pricingCalc.coupon_discount_amount}`}
</span>
</div>
)}
{pricingCalc.total_discounts > 0 &&
!pricingCalc.bundle_discount_amount &&
!pricingCalc.coupon_discount_amount && (
<div className="flex justify-between text-xs text-emerald-700 font-bold">
<span>Total Discounts</span>
<span>
-{currency === 'INR'
? `₹${pricingCalc.total_discounts}`
: currency === 'EUR'
? `€${pricingCalc.total_discounts}`
: `$${pricingCalc.total_discounts}`}
</span>
</div>
)}
{pricingCalc.convenience_fee > 0 && (
<div className="flex justify-between text-xs text-slate-600 font-bold">
<span>Gateway fee ({pricingCalc.convenience_fee_rate}%)</span>

View File

@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import { XCircle, CheckCircle, Check, Download, RefreshCw, Smartphone } from 'lucide-react';
import type { VerificationResult, UserProfile } from '../../types';
import { openMobileApp, getAppDeepLinkUrls } from '../../utils/navigation';
@ -22,6 +22,42 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
returnRoute,
appScheme,
}) => {
const [desktopNotice, setDesktopNotice] = useState(false);
// Handler to reliably launch the Acupedia Mobile App across platforms (Android, iOS, and Desktop)
const handleOpenApp = (e: React.MouseEvent) => {
e.preventDefault();
const userAgent = navigator.userAgent || '';
const isAndroid = /Android/i.test(userAgent);
const isIOS = /iPhone|iPad|iPod/i.test(userAgent);
if (isAndroid) {
// Android Chrome requires an Intent URI format to launch apps by package and scheme reliably
const intentUrl = 'intent://#Intent;scheme=acupedia;package=com.anonymous.acupedia;end';
window.location.href = intentUrl;
// Fallback to custom URI schemes in case intent fails or Expo uses alternate scheme
setTimeout(() => {
window.location.href = 'acupedia://';
}, 500);
setTimeout(() => {
window.location.href = 'myapp://';
}, 1000);
} else if (isIOS) {
// iOS Safari and Chrome handle custom URI schemes directly
window.location.href = 'acupedia://';
// Fallback in case Expo uses default 'myapp://' scheme
setTimeout(() => {
window.location.href = 'myapp://';
}, 500);
} else {
// On desktop browsers, try opening the registered custom scheme
window.location.href = 'acupedia://';
// Show helpful desktop feedback informing the user how to access content on mobile
setDesktopNotice(true);
}
};
return (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/75 backdrop-blur-md transition-all duration-300">
<div className="relative w-full max-w-xl bg-slate-900 border border-slate-800 rounded-2xl p-5 md:p-6 space-y-4 shadow-2xl text-slate-100 overflow-hidden animate-in fade-in zoom-in-95 duration-200">
@ -180,17 +216,27 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
</button>
)}
<a
href={getAppDeepLinkUrls({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined })[0]}
onClick={(e) => {
e.preventDefault();
openMobileApp({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined });
}}
className="w-full h-9 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-emerald-600/10 no-underline decoration-0 cursor-pointer"
>
<Smartphone className="h-3.5 w-3.5 text-emerald-200" />
Open in App / Library
</a>
{/* Open in App Button */}
{/* Open in App Button */}
<a
href={getAppDeepLinkUrls({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined })[0]}
onClick={(e) => {
e.preventDefault();
openMobileApp({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined });
}}
className="w-full h-9 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-emerald-600/10 no-underline decoration-0 cursor-pointer"
>
<Smartphone className="h-3.5 w-3.5 text-emerald-200" />
Open in App / Library
</a>
{desktopNotice && (
<div className="p-2.5 bg-slate-950 border border-emerald-900/40 rounded-lg text-center animate-in fade-in duration-200">
<p className="text-[11px] text-emerald-400 font-medium">
📱 Attempted to launch Acupedia App. If you are on desktop, please open the Acupedia App on your mobile device to view your unlocked content.
</p>
</div>
)}
<button
onClick={onClose}

View File

@ -1,23 +1,69 @@
import type { Currency } from '../types';
export interface CountryCode {
code: string;
label: string;
country: string;
currency: Currency;
minLength: number;
maxLength: number;
placeholder: string;
}
export const COUNTRY_CODES: CountryCode[] = [
{ code: '+91', label: '🇮🇳 +91', country: 'India' },
{ code: '+1', label: '🇺🇸 +1', country: 'US' },
{ code: '+44', label: '🇬🇧 +44', country: 'UK' },
{ code: '+61', label: '🇦🇺 +61', country: 'AU' },
{ code: '+49', label: '🇩🇪 +49', country: 'DE' },
{ code: '+33', label: '🇫🇷 +33', country: 'FR' },
{ code: '+81', label: '🇯🇵 +81', country: 'JP' },
{ code: '+86', label: '🇨🇳 +86', country: 'CN' },
{ code: '+971', label: '🇦🇪 +971', country: 'UAE' },
{ code: '+65', label: '🇸🇬 +65', country: 'SG' },
{ code: '+55', label: '🇧🇷 +55', country: 'BR' },
{ code: '+82', label: '🇰🇷 +82', country: 'KR' },
{ code: '+7', label: '🇷🇺 +7', country: 'RU' },
{ code: '+27', label: '🇿🇦 +27', country: 'ZA' },
{ code: '+234', label: '🇳🇬 +234', country: 'NG' },
{ code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
{ code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' },
{ code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
{ code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
{ code: '+49', label: '🇩🇪 +49', country: 'Germany', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
{ code: '+33', label: '🇫🇷 +33', country: 'France', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
{ code: '+81', label: '🇯🇵 +81', country: 'Japan', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
{ code: '+86', label: '🇨🇳 +86', country: 'China', currency: 'USD', minLength: 11, maxLength: 11, placeholder: '11-digit mobile number' },
{ code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
{ code: '+65', label: '🇸🇬 +65', country: 'Singapore', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
{ code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
{ code: '+82', label: '🇰🇷 +82', country: 'South Korea', currency: 'USD', minLength: 9, maxLength: 11, placeholder: '9 to 11 digits' },
{ code: '+7', label: '🇷🇺 +7', country: 'Russia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
{ code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
{ code: '+234', label: '🇳🇬 +234', country: 'Nigeria', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
];
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
export const getCountryRuleByDialCode = (dialCode: string): CountryCode => {
return (
COUNTRY_CODES.find((c) => c.code === dialCode) || {
code: dialCode,
label: dialCode,
country: 'Other',
currency: 'USD',
minLength: 6,
maxLength: 15,
placeholder: 'Phone number',
}
);
};
export const getCountryRuleByName = (countryName: string): CountryCode => {
if (!countryName) return DEFAULT_COUNTRY;
const normalized = countryName.toLowerCase();
return (
COUNTRY_CODES.find(
(c) =>
c.country.toLowerCase() === normalized ||
(normalized.includes('india') && c.country === 'India') ||
(normalized.includes('united states') && c.country === 'United States') ||
(normalized.includes('united kingdom') && c.country === 'United Kingdom') ||
(normalized.includes('germany') && c.country === 'Germany') ||
(normalized.includes('australia') && c.country === 'Australia')
) || {
code: '+91',
label: '🇮🇳 +91',
country: countryName,
currency: normalized === 'india' ? 'INR' : 'USD',
minLength: 6,
maxLength: 15,
placeholder: 'Phone number',
}
);
};

76
src/utils/validation.ts Normal file
View File

@ -0,0 +1,76 @@
import { getCountryRuleByDialCode, getCountryRuleByName } from '../constants/countries';
/**
* Strips non-numeric / non-phone characters from text in real-time
* If maxLength is provided, strictly restricts digit length
*/
export const cleanPhoneInput = (text: string, maxLength?: number): string => {
const trimmedStart = text.trimStart();
const hasPlus = 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;
};
/**
* Validates phone number according to country rules (e.g. India = exactly 10 digits)
*/
export const validatePhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): string | null => {
if (!val || !val.trim()) return null;
const trimmed = val.trim();
const digits = trimmed.replace(/\D/g, '');
if (digits.length === 0) {
return 'Please enter a valid phone number with numeric digits.';
}
// Resolve country rule by dial code or country name
let rule = dialCode ? getCountryRuleByDialCode(dialCode) : undefined;
if ((!rule || rule.country === 'Other') && country) {
rule = getCountryRuleByName(country);
}
// Default to India if no specific rule resolved and dial code is +91 or country is India
if (!rule || rule.country === 'Other') {
if (dialCode === '+91' || (country && country.toLowerCase() === 'india')) {
rule = getCountryRuleByDialCode('+91');
}
}
if (rule && rule.country !== 'Other') {
if (rule.minLength === rule.maxLength) {
if (digits.length !== rule.minLength) {
return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
}
} else {
if (digits.length < rule.minLength) {
return `${rule.country} phone number must be at least ${rule.minLength} digits.`;
}
if (digits.length > rule.maxLength) {
return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`;
}
}
return null;
}
// General fallback ITU E.164
if (digits.length < 6) {
return 'Phone number must contain at least 6 digits.';
}
if (digits.length > 15) {
return 'Phone number cannot exceed 15 digits.';
}
return null;
};
export const isValidPhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): boolean => {
return validatePhoneNumber(val, dialCode, country) === null;
};