45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
|
|
/** Canonical Iran mobile: +989XXXXXXXXX */
|
||
|
|
export const IR_MOBILE_REGEX = /^\+989\d{9}$/;
|
||
|
|
|
||
|
|
export function normalizeMobile(input: string): string | null {
|
||
|
|
const trimmed = input?.trim();
|
||
|
|
if (!trimmed) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
let digits = trimmed.replace(/[^\d+]/g, '');
|
||
|
|
if (digits.startsWith('+')) {
|
||
|
|
digits = digits.slice(1);
|
||
|
|
}
|
||
|
|
|
||
|
|
digits = digits.replace(/\D/g, '');
|
||
|
|
|
||
|
|
if (digits.startsWith('0098')) {
|
||
|
|
digits = digits.slice(4);
|
||
|
|
} else if (digits.startsWith('98') && digits.length >= 12) {
|
||
|
|
digits = digits.slice(2);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (digits.startsWith('0') && digits.length === 11) {
|
||
|
|
digits = digits.slice(1);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (digits.length === 10 && digits.startsWith('9')) {
|
||
|
|
return `+98${digits}`;
|
||
|
|
}
|
||
|
|
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function isValidMobile(normalized: string): boolean {
|
||
|
|
return IR_MOBILE_REGEX.test(normalized);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function formatMobileForDisplay(normalized: string): string {
|
||
|
|
if (!isValidMobile(normalized)) {
|
||
|
|
return normalized;
|
||
|
|
}
|
||
|
|
const local = `0${normalized.slice(3)}`;
|
||
|
|
return `${local.slice(0, 4)} ${local.slice(4, 7)} ${local.slice(7)}`;
|
||
|
|
}
|