Files
dukang/apps/mini-user/src/lib/user-phone.ts
T
2026-07-12 20:24:03 +08:00

39 lines
1.1 KiB
TypeScript

import Taro from '@tarojs/taro';
import { normalizePhoneInput } from './phone';
const USER_PHONE_KEY = 'user_phone';
function isValidMobile(phone: string) {
return /^1[3-9]\d{9}$/.test(phone);
}
export function saveUserPhone(phone: string) {
const normalized = normalizePhoneInput(phone);
if (!isValidMobile(normalized)) return;
try {
Taro.setStorageSync(USER_PHONE_KEY, normalized);
} catch {
/* ignore */
}
}
export function getStoredUserPhone(): string {
try {
const value = Taro.getStorageSync(USER_PHONE_KEY);
return typeof value === 'string' ? value : '';
} catch {
return '';
}
}
/** 新增地址等场景:优先本地缓存,其次资料里的已验证手机号 */
export function resolveDefaultUserPhone(profile?: { phone?: string | null; phoneVerified?: boolean } | null) {
const stored = getStoredUserPhone();
if (isValidMobile(stored)) return stored;
if (!profile?.phoneVerified || !profile.phone) return '';
const fromProfile = normalizePhoneInput(profile.phone);
if (!isValidMobile(fromProfile)) return '';
saveUserPhone(fromProfile);
return fromProfile;
}