Compare commits

..

No commits in common. "2aceec4c37014cad0922b1b6a76dd967e9d1cfb3" and "401ebb40d5ada7881e12cd25dadd4e72cf739025" have entirely different histories.

8 changed files with 219 additions and 268 deletions

7
package-lock.json generated
View File

@ -9,7 +9,6 @@
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"axios": "^1.7.0", "axios": "^1.7.0",
"libphonenumber-js": "^1.13.16",
"lucide-react": "^0.460.0", "lucide-react": "^0.460.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0"
@ -3456,12 +3455,6 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/libphonenumber-js": {
"version": "1.13.16",
"resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.16.tgz",
"integrity": "sha512-tIOCM9yx2Go6d5/ZANe0K+G4AZek1Ymx81HxQpf19Sri4zMP95eQbKdnUGHAvFQ4nx0PeLhFqvAfisTADXj3tQ==",
"license": "MIT"
},
"node_modules/lightningcss": { "node_modules/lightningcss": {
"version": "1.32.0", "version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",

View File

@ -11,7 +11,6 @@
}, },
"dependencies": { "dependencies": {
"axios": "^1.7.0", "axios": "^1.7.0",
"libphonenumber-js": "^1.13.16",
"lucide-react": "^0.460.0", "lucide-react": "^0.460.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0"

View File

@ -379,7 +379,7 @@ export default function App() {
setProfileSaving(false); setProfileSaving(false);
return; return;
} }
cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits, profileCountry); cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits);
} }
try { try {
@ -472,7 +472,8 @@ export default function App() {
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
fullPhone = formatE164Phone(authDialCode, authPhone, authCountry); 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';
@ -881,7 +882,7 @@ export default function App() {
// Sanitize contact for Razorpay: strictly E.164 (+<dialCode><digits>) // Sanitize contact for Razorpay: strictly E.164 (+<dialCode><digits>)
const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India'); const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India');
const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits, loggedInUser?.country || 'India'); const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits);
const rzpOptions = { const rzpOptions = {
key: razorpayKeyId, key: razorpayKeyId,

View File

@ -94,7 +94,7 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
const handleLocalPhoneChange = (newLocal: string) => { const handleLocalPhoneChange = (newLocal: string) => {
setLocalPhone(newLocal); setLocalPhone(newLocal);
setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal, profileCountry) : ''); setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal) : '');
}; };
const handleDialCodeChange = (newCode: string, newCountry: string) => { const handleDialCodeChange = (newCode: string, newCountry: string) => {
@ -104,7 +104,7 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
setCurrency(rule.currency); setCurrency(rule.currency);
const clamped = cleanPhoneInput(localPhone, rule.maxLength, false); const clamped = cleanPhoneInput(localPhone, rule.maxLength, false);
setLocalPhone(clamped); setLocalPhone(clamped);
setProfilePhone(formatE164Phone(newCode, clamped, newCountry)); setProfilePhone(formatE164Phone(newCode, clamped));
}; };
const handleCountrySelectChange = (newCountry: string) => { const handleCountrySelectChange = (newCountry: string) => {
@ -114,7 +114,7 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
setCurrency(rule.currency); setCurrency(rule.currency);
const clamped = cleanPhoneInput(localPhone, rule.maxLength, false); const clamped = cleanPhoneInput(localPhone, rule.maxLength, false);
setLocalPhone(clamped); setLocalPhone(clamped);
setProfilePhone(formatE164Phone(rule.code, clamped, newCountry)); setProfilePhone(formatE164Phone(rule.code, clamped));
}; };
if (!isOpen || !loggedInUser) return null; if (!isOpen || !loggedInUser) return null;

View File

@ -53,7 +53,7 @@ export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
} }
setSaving(true); setSaving(true);
const e164 = formatE164Phone(dialCode, phone, country); const e164 = formatE164Phone(dialCode, phone);
try { try {
const success = await onSavePhone(e164, country); const success = await onSavePhone(e164, country);
if (success) { if (success) {

View File

@ -27,24 +27,24 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
id = 'phone-input', id = 'phone-input',
clearOnDialCodeChange = false, clearOnDialCodeChange = false,
}) => { }) => {
// Prioritize country name if available, fallback to dial code let activeRule = getCountryRuleByDialCode(dialCode);
let activeRule = country ? getCountryRuleByName(country) : undefined; if (!activeRule && country) {
if (!activeRule && dialCode) { activeRule = getCountryRuleByName(country);
activeRule = getCountryRuleByDialCode(dialCode, country);
} }
if (!activeRule) { if (!activeRule) {
activeRule = getCountryRuleByDialCode('+91')!; activeRule = getCountryRuleByDialCode('+91')!;
} }
const handleCountrySelect = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleDialCodeSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
const selectedCountryName = e.target.value; const newCode = e.target.value;
const rule = getCountryRuleByName(selectedCountryName); const rule = getCountryRuleByDialCode(newCode);
const newCountry = rule ? rule.country : (country || 'India');
if (onDialCodeChange) { if (onDialCodeChange) {
onDialCodeChange(rule.code, rule.country); onDialCodeChange(newCode, newCountry);
} }
if (clearOnDialCodeChange) { if (clearOnDialCodeChange) {
onPhoneChange(''); onPhoneChange('');
} else { } else if (rule) {
onPhoneChange(cleanPhoneInput(phone, rule.maxLength, false)); onPhoneChange(cleanPhoneInput(phone, rule.maxLength, false));
} }
}; };
@ -58,7 +58,7 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length); const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
const matched = sorted.find((c) => trimmed.startsWith(c.code)); const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) { if (matched) {
if (onDialCodeChange && (matched.code !== dialCode || matched.country !== country)) { if (onDialCodeChange && matched.code !== dialCode) {
onDialCodeChange(matched.code, matched.country); onDialCodeChange(matched.code, matched.country);
} }
const rest = trimmed.slice(matched.code.length).replace(/\D/g, ''); const rest = trimmed.slice(matched.code.length).replace(/\D/g, '');
@ -108,11 +108,11 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
return ( return (
<div className="space-y-1.5 w-full"> <div className="space-y-1.5 w-full">
<div className="flex gap-2 w-full"> <div className="flex gap-2 w-full">
{/* Country Code Dropdown: keyed by unique country name to avoid +1 (US vs CA) collisions */} {/* Country Code Dropdown */}
<div className="relative shrink-0 w-[110px]"> <div className="relative shrink-0 w-[105px]">
<select <select
value={activeRule.country} value={dialCode}
onChange={handleCountrySelect} onChange={handleDialCodeSelect}
disabled={disabled} disabled={disabled}
className={`w-full rounded-xl px-2.5 py-2.5 text-xs font-semibold appearance-none pr-6 cursor-pointer focus:outline-none transition-colors ${ className={`w-full rounded-xl px-2.5 py-2.5 text-xs font-semibold appearance-none pr-6 cursor-pointer focus:outline-none transition-colors ${
isDark isDark
@ -121,7 +121,7 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`} } ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
> >
{COUNTRY_CODES.map((cc) => ( {COUNTRY_CODES.map((cc) => (
<option key={`${cc.country}-${cc.code}`} value={cc.country}> <option key={`${cc.country}-${cc.code}`} value={cc.code}>
{cc.label} ({cc.country}) {cc.label} ({cc.country})
</option> </option>
))} ))}
@ -151,11 +151,23 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
/> />
</div> </div>
{error && ( {/* Helper text or Error message */}
<p className="text-[11px] font-semibold text-rose-500 animate-shake"> <div className="flex justify-between items-center text-[10px] px-0.5">
{error} {error ? (
</p> <p className="text-rose-500 font-bold">{error}</p>
)} ) : (
<p className={isDark ? 'text-slate-400 font-medium' : 'text-slate-500 font-medium'}>
{activeRule.label || activeRule.country}:{' '}
{activeRule.minLength === activeRule.maxLength
? `Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
)}
<span className={`font-mono font-semibold ${phone.length === activeRule.maxLength ? 'text-emerald-500' : isDark ? 'text-slate-500' : 'text-slate-400'}`}>
{phone.length}/{activeRule.maxLength}
</span>
</div>
</div> </div>
); );
}; };

View File

@ -1,8 +1,6 @@
import type { CountryCode as LibCountryCode } from 'libphonenumber-js';
import type { Currency } from '../types'; import type { Currency } from '../types';
export interface CountryCode { export interface CountryCode {
iso2: LibCountryCode;
code: string; code: string;
label: string; label: string;
country: string; country: string;
@ -14,90 +12,90 @@ export interface CountryCode {
export const COUNTRY_CODES: CountryCode[] = [ export const COUNTRY_CODES: CountryCode[] = [
// South Asia // South Asia
{ iso2: 'IN', code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { code: '+960', label: '🇲🇻 +960', country: 'Maldives', currency: 'USD', minLength: 7, maxLength: 7, placeholder: '7-digit mobile number' },
// North America // North America
{ iso2: 'US', code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' }, { 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' }, { 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' }, { code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
// Europe & UK // Europe & UK
{ iso2: 'GB', code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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: 7, maxLength: 10, placeholder: '7 to 10 digits' }, { code: '+358', label: '🇫🇮 +358', country: 'Finland', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits' },
{ iso2: 'PT', code: '+351', label: '🇵🇹 +351', country: 'Portugal', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { code: '+90', label: '🇹🇷 +90', country: 'Turkey', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
// Asia-Pacific // Asia-Pacific
{ iso2: 'AU', code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { code: '+84', label: '🇻🇳 +84', country: 'Vietnam', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
// Middle East // Middle East
{ iso2: 'AE', code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { code: '+961', label: '🇱🇧 +961', country: 'Lebanon', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits' },
// Latin America // Latin America
{ iso2: 'BR', code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, { 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' }, { 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' }, { 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' }, { 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' }, { code: '+51', label: '🇵🇪 +51', country: 'Peru', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
// Africa // Africa
{ iso2: 'ZA', code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { 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' }, { code: '+230', label: '🇲🇺 +230', country: 'Mauritius', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits' },
]; ];
// Alphabetically sorted list of countries (A-Z) // Alphabetically sorted list of countries (A-Z)
@ -107,23 +105,29 @@ export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91) export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
export const getCountryRuleByIso = (iso?: string | null): CountryCode => { export const getCountryRuleByDialCode = (dialCode: string): CountryCode => {
if (!iso) return DEFAULT_COUNTRY; return (
const upper = iso.toUpperCase().trim(); COUNTRY_CODES.find((c) => c.code === dialCode) || {
return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY; code: dialCode,
label: dialCode,
country: 'Other',
currency: 'USD',
minLength: 7,
maxLength: 15,
placeholder: 'Phone number',
}
);
}; };
export const getCountryRuleByName = (countryName?: string | null): CountryCode => { export const getCountryRuleByName = (countryName: string): CountryCode => {
if (!countryName) return DEFAULT_COUNTRY; if (!countryName) return DEFAULT_COUNTRY;
const normalized = countryName.toLowerCase().trim(); const normalized = countryName.toLowerCase().trim();
return ( return (
COUNTRY_CODES.find( COUNTRY_CODES.find(
(c) => (c) =>
c.country.toLowerCase() === normalized || c.country.toLowerCase() === normalized ||
c.iso2.toLowerCase() === normalized ||
normalized.includes(c.country.toLowerCase()) normalized.includes(c.country.toLowerCase())
) || { ) || {
iso2: 'IN',
code: '+91', code: '+91',
label: '🇮🇳 +91', label: '🇮🇳 +91',
country: countryName, country: countryName,
@ -134,26 +138,3 @@ export const getCountryRuleByName = (countryName?: string | null): CountryCode =
} }
); );
}; };
export const getCountryRuleByDialCode = (dialCode?: string | null, countryHint?: string | null): CountryCode => {
if (!dialCode) return DEFAULT_COUNTRY;
// If country hint is given, try resolving by country first
if (countryHint) {
const byCountry = getCountryRuleByName(countryHint);
if (byCountry && byCountry.code === dialCode) {
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',
}
);
};

View File

@ -1,11 +1,4 @@
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from 'libphonenumber-js/max'; import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../constants/countries';
import {
COUNTRY_CODES,
getCountryRuleByDialCode,
getCountryRuleByName,
getCountryRuleByIso,
DEFAULT_COUNTRY,
} from '../constants/countries';
/** /**
* Strips non-numeric / non-phone characters from text in real-time * Strips non-numeric / non-phone characters from text in real-time
@ -22,8 +15,8 @@ export const cleanPhoneInput = (text: string, maxLength = 15, allowPlus = true):
}; };
/** /**
* Validates mobile phone number according to country telecom numbering plans. * Validates phone number according to country rules (e.g. India = exactly 10 digits)
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07). * Strictly disallows alphabetic characters and invalid symbols
*/ */
export const validatePhoneNumber = ( export const validatePhoneNumber = (
val?: string | null, val?: string | null,
@ -38,8 +31,8 @@ export const validatePhoneNumber = (
return 'Phone number cannot contain alphabetic characters.'; return 'Phone number cannot contain alphabetic characters.';
} }
// Strictly disallow hyphens, dashes, and invalid symbols // Strictly disallow hyphens, dashes, and invalid characters
if (/[\-_()/[\]]/.test(trimmed)) { if (/[\-()_]/.test(trimmed)) {
return 'Phone number cannot contain hyphens or special symbols.'; return 'Phone number cannot contain hyphens or special symbols.';
} }
@ -53,89 +46,69 @@ export const validatePhoneNumber = (
return 'Please enter a valid phone number with numeric digits.'; return 'Please enter a valid phone number with numeric digits.';
} }
// Resolve country rule: prioritize explicit country name, fallback to dialCode // Resolve country rule by dial code or country name
let rule = country ? getCountryRuleByName(country) : undefined; let rule = dialCode ? getCountryRuleByDialCode(dialCode) : undefined;
if (!rule && dialCode) { if ((!rule || rule.country === 'Other') && country) {
rule = getCountryRuleByDialCode(dialCode, country); rule = getCountryRuleByName(country);
} }
if (!rule) { // If still not found and input starts with '+', match from COUNTRY_CODES
rule = DEFAULT_COUNTRY; 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));
}
// 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');
}
} }
const iso2 = rule.iso2 || 'IN'; if (rule && rule.country !== 'Other') {
const dialDigits = rule.code.replace(/\D/g, '');
let localDigits = allDigits;
// Extract national digits without dial code prefix if (trimmed.startsWith('+')) {
let nationalDigits = allDigits; // Input includes country code prefix (e.g. +919876543210 or +9198765432)
const dialDigits = rule.code.replace(/\D/g, ''); // Must strip the dial code to extract the actual local number
if (trimmed.startsWith('+')) { if (allDigits.startsWith(dialDigits)) {
if (allDigits.startsWith(dialDigits)) { localDigits = allDigits.slice(dialDigits.length);
nationalDigits = 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);
} }
} else if (allDigits.startsWith(dialDigits) && allDigits.length > rule.maxLength) {
nationalDigits = allDigits.slice(dialDigits.length);
}
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 (rule.minLength === rule.maxLength) {
if (digitsWithoutTrunk0.length !== rule.minLength && nationalDigits.length !== rule.minLength) { if (localDigits.length !== rule.minLength) {
return `${rule.country} mobile number must be exactly ${rule.minLength} digits.`; return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
} }
} else { } else {
if (digitsWithoutTrunk0.length < rule.minLength && nationalDigits.length < rule.minLength) { if (localDigits.length < rule.minLength) {
return `${rule.country} mobile number is too short (min ${rule.minLength} digits).`; return `${rule.country} phone number must be at least ${rule.minLength} digits.`;
} }
if (digitsWithoutTrunk0.length > rule.maxLength) { if (localDigits.length > rule.maxLength) {
return `${rule.country} mobile number cannot exceed ${rule.maxLength} digits.`; return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`;
} }
} }
}
// 2. Validate telecom numbering rules with libphonenumber-js // Specific country telecom prefix rules
const candidate = trimmed.startsWith('+') ? trimmed : `${rule.code}${nationalDigits}`; if (dialDigits === '91' || rule.country === 'India') {
const parsed = parsePhoneNumberFromString(candidate, iso2); if (!/^[6-9]/.test(localDigits)) {
return 'India mobile number must begin with 6, 7, 8, or 9.';
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 null;
} }
return `Please enter a valid mobile number for ${rule.country} (e.g. ${rule.placeholder}).`; // General fallback ITU E.164
if (allDigits.length < 7) {
return 'Phone number must contain at least 7 digits.';
}
if (allDigits.length > 15) {
return 'Phone number cannot exceed 15 digits.';
}
return null;
}; };
export const isValidPhoneNumber = ( export const isValidPhoneNumber = (
@ -152,34 +125,14 @@ export const isValidPhoneNumber = (
export const parsePhoneNumber = ( export const parsePhoneNumber = (
fullPhone?: string | null, fullPhone?: string | null,
fallbackCountry = 'India' fallbackCountry = 'India'
): { country: string; dialCode: string; localDigits: string; iso2: LibCountryCode } => { ): { country: string; dialCode: string; localDigits: string } => {
const defaultRule = getCountryRuleByName(fallbackCountry) || DEFAULT_COUNTRY; const defaultRule = getCountryRuleByName(fallbackCountry) || getCountryRuleByDialCode('+91')!;
if (!fullPhone || !fullPhone.trim()) { if (!fullPhone || !fullPhone.trim()) {
return { return { country: defaultRule.country, dialCode: defaultRule.code, localDigits: '' };
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: '',
iso2: defaultRule.iso2,
};
} }
const trimmed = fullPhone.trim(); const trimmed = fullPhone.trim();
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
if (parsed) { // Try matching dial code prefixes from longest to shortest
const matchedRule = parsed.country
? getCountryRuleByIso(parsed.country)
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
return {
country: matchedRule.country,
dialCode: `+${parsed.countryCallingCode}`,
localDigits: parsed.nationalNumber,
iso2: matchedRule.iso2,
};
}
// Fallback regex match from longest dial code
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length); const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
const matched = sorted.find((c) => trimmed.startsWith(c.code)); const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) { if (matched) {
@ -188,44 +141,34 @@ export const parsePhoneNumber = (
country: matched.country, country: matched.country,
dialCode: matched.code, dialCode: matched.code,
localDigits: rawLocal.slice(0, matched.maxLength), localDigits: rawLocal.slice(0, matched.maxLength),
iso2: matched.iso2,
}; };
} }
// 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, ''); const rawDigits = trimmed.replace(/\D/g, '');
let local = rawDigits;
if (
dialDigits &&
rawDigits.startsWith(dialDigits) &&
rawDigits.length > defaultRule.maxLength
) {
local = rawDigits.slice(dialDigits.length);
}
return { return {
country: defaultRule.country, country: defaultRule.country,
dialCode: defaultRule.code, dialCode: defaultRule.code,
localDigits: rawDigits.slice(0, defaultRule.maxLength), localDigits: local.slice(0, defaultRule.maxLength),
iso2: defaultRule.iso2,
}; };
}; };
/** /**
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>), * 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 => { export const formatE164Phone = (dialCode: string, localDigits: string): string => {
if (!localDigits || !localDigits.trim()) return ''; const digits = localDigits.replace(/\D/g, '');
const rule = country ? getCountryRuleByName(country) : getCountryRuleByDialCode(dialCode, country);
const rawDigits = localDigits.replace(/\D/g, '');
if (!rawDigits) return '';
const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`; const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`;
const candidate = localDigits.startsWith('+') ? localDigits : `${code}${rawDigits}`; return digits ? `${code}${digits}` : '';
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
if (parsed && parsed.isValid()) {
return parsed.format('E.164');
}
// Fallback: If starts with trunk 0 and country is not one that keeps trunk 0 (like Italy)
let cleanLocal = rawDigits;
if (rule.iso2 !== 'IT' && cleanLocal.startsWith('0')) {
cleanLocal = cleanLocal.replace(/^0+/, '');
}
return `${code}${cleanLocal}`;
}; };
/** /**
@ -243,8 +186,27 @@ export const updatePhoneDialCode = (
const oldRule = getCountryRuleByName(oldCountry); const oldRule = getCountryRuleByName(oldCountry);
const newRule = getCountryRuleByName(newCountry); const newRule = getCountryRuleByName(newCountry);
const parsed = parsePhoneNumber(trimmed, oldRule.country); let nationalDigits = '';
const bounded = parsed.localDigits.slice(0, newRule.maxLength); if (trimmed.startsWith('+')) {
const matched = [...COUNTRY_CODES]
.sort((a, b) => b.code.length - a.code.length)
.find((c) => trimmed.startsWith(c.code));
if (matched) {
nationalDigits = trimmed.slice(matched.code.length).replace(/\D/g, '');
} else {
nationalDigits = trimmed.replace(/^\+/, '').replace(/\D/g, '');
}
} else {
const oldDialDigits = oldRule.code.replace(/\D/g, '');
const rawDigits = trimmed.replace(/\D/g, '');
if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldDialDigits.length) {
nationalDigits = rawDigits.slice(oldDialDigits.length);
} else {
nationalDigits = rawDigits;
}
}
const bounded = nationalDigits.slice(0, newRule.maxLength);
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `; return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
}; };
@ -286,6 +248,8 @@ export const validatePassword = (password: string, fieldName = 'Password'): stri
/** /**
* RFC 5322 & RFC 1035 compliant email validation regex. * RFC 5322 & RFC 1035 compliant email validation regex.
* Disallows invalid domain characters (e.g. + in domain like +gmail+.com, consecutive dots, leading/trailing hyphens)
* while properly accepting plus-addressing in local-part (e.g. sanskar+sarak@gmail.com).
*/ */
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-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,}$/;
@ -302,3 +266,4 @@ export const validateEmail = (email?: string | null): string | null => {
export const isValidEmail = (email?: string | null): boolean => { export const isValidEmail = (email?: string | null): boolean => {
return validateEmail(email) === null; return validateEmail(email) === null;
}; };