Files
dukang/apps/mini-user/src/lib/phone.ts
T
jacy cc750dc1d6 feat: v3.4.18 门店体验与登录态优化
- mini-user 门店座机电话中间四位脱敏(保留区号与前后位)
- mini-user 套餐详情图增加 1/N 计数与自动轮播
- h5-partner 账号暂停(DISABLED)禁止登录并提示客服
- h5-shop 提现/筛选栏左右留白与页面一致
- h5-shop 休息中核销改为弹「是否开启营业」并支持开张后继续

Co-Authored-By: WorkBuddy <workbuddy@tencent.com>
2026-08-17 21:34:40 +08:00

67 lines
2.5 KiB
TypeScript

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, '');
}