Files
stream-demo-standalone/src/lib/phoneRu.ts
T
2026-04-10 17:16:13 +05:00

65 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { getExampleNumber } from "libphonenumber-js";
import examples from "libphonenumber-js/mobile/examples";
export const PHONE_CODE_RU = "+7";
export const PHONE_COUNTRY_RU = "RU" as const;
/** Локальная часть примера номера (без кода страны) для маски */
export function getRuMobileExampleLocal(): string | undefined {
return getExampleNumber(PHONE_COUNTRY_RU, examples)
?.formatInternational()
.split(" ")
.slice(1)
.join(" ");
}
export function buildRuPhoneMask(placeholderLocal: string | undefined): string {
return `${PHONE_CODE_RU} ${(placeholderLocal?.replace(/\d/g, "9") ?? "")}`;
}
/** Только цифры: 7 + до 10 цифр номера (без +) */
export function ruPhoneDigits(stored: string): string {
let d = stored.replace(/\D/g, "");
if (d.startsWith("8")) d = "7" + d.slice(1);
if (d.length === 0) return "";
if (!d.startsWith("7")) d = "7" + d;
return d.slice(0, 11);
}
/** Отображение +7 (XXX) XXX-XX-XX без react-input-mask (совместимо с React 19) */
export function formatRuPhoneDisplay(stored: string): string {
const d = ruPhoneDigits(stored);
if (!d) return "";
const n = d.slice(1);
if (n.length === 0) return "+7";
const a = n.slice(0, 3);
const b = n.slice(3, 6);
const c = n.slice(6, 8);
const e = n.slice(8, 10);
let s = "+7 (" + a;
if (n.length <= 3) return s;
s += ") " + b;
if (n.length <= 6) return s;
s += "-" + c;
if (n.length <= 8) return s;
s += "-" + e;
return s;
}
export function normalizeRuPhoneFromInput(
cleanValue: string,
inputType: string | undefined
): string {
const shouldAddPhoneCode =
inputType !== "insertFromPaste" &&
inputType !== "insertFromDrop" &&
inputType !== "insertCompositionText" &&
!cleanValue.startsWith("+") &&
!cleanValue.startsWith("7") &&
!cleanValue.startsWith(PHONE_CODE_RU.replace("+", ""));
return (shouldAddPhoneCode ? PHONE_CODE_RU : "") + cleanValue;
}