const MOBILE_PHONE_RE = /^1[3-9]\d{9}$/; const LANDLINE_PHONE_RE = /^0\d{2,3}-?\d{7,8}(-\d{1,6})?$/; export function normalizePhoneInput(value: string): string { return value.replace(/\D/g, '').slice(0, 11); } export function validateMobilePhone(phone: string): { ok: boolean; message?: string } { const trimmed = phone.trim(); if (!trimmed) { return { ok: false, message: '请输入手机号码' }; } if (trimmed.length !== 11) { return { ok: false, message: '手机号码须为 11 位' }; } if (!MOBILE_PHONE_RE.test(trimmed)) { return { ok: false, message: '请输入正确的手机号码' }; } return { ok: true }; } function normalizeContactPhone(raw: string): string { return String(raw ?? '') .trim() .replace(/\s+/g, ''); } /** * 脱敏展示:手机 138****8000;座机隐藏本地号中间四位,如 0379-12****78。 * 门店详情电话展示用(拨号仍走 toDialablePhone 明文)。 */ export function maskPhone(phone: string) { const normalized = normalizeContactPhone(phone); if (!normalized) return ''; if (MOBILE_PHONE_RE.test(normalized)) { const digits = normalized.replace(/\D/g, ''); return `${digits.slice(0, 3)}****${digits.slice(-4)}`; } if (LANDLINE_PHONE_RE.test(normalized)) { const extMatch = normalized.match(/-(\d{1,6})$/); const hasExt = !!extMatch && normalized.indexOf('-') !== normalized.lastIndexOf('-'); const ext = hasExt ? extMatch![1] : ''; const main = hasExt ? normalized.slice(0, -(ext.length + 1)) : normalized; const digits = main.replace(/\D/g, ''); const areaLen = digits.startsWith('01') || digits.startsWith('02') ? 3 : 4; const area = digits.slice(0, areaLen); const local = digits.slice(areaLen); // 隐藏本地号中间四位(保留区号,本号前后各留若干位):0379-12345678 → 0379-12****78 let maskedLocal: string; if (local.length <= 4) { maskedLocal = '*'.repeat(local.length); } else { const keep = local.length - 4; const head = Math.max(1, Math.floor(keep / 2)); const tail = keep - head; maskedLocal = `${local.slice(0, head)}${'*'.repeat(4)}${local.slice(local.length - tail)}`; } const joiner = main.includes('-') ? '-' : ''; return ext ? `${area}${joiner}${maskedLocal}-${ext}` : `${area}${joiner}${maskedLocal}`; } return normalized.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'); } export function toDialablePhone(raw: string): string { return String(raw ?? '').replace(/[\s-]/g, ''); }