rwadurian/backend/services/identity-service/src/domain/value-objects/phone-number.vo.ts

35 lines
808 B
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 { DomainException } from '@shared/exceptions/domain.exception';
export class PhoneNumber {
private readonly _value: string;
private constructor(value: string) {
const normalized = value.replace(/\s+/g, '');
if (!/^1[3-9]\d{9}$/.test(normalized)) {
throw new DomainException('手机号格式错误必须是11位中国大陆手机号');
}
this._value = normalized;
}
static create(value: string): PhoneNumber {
return new PhoneNumber(value);
}
get value(): string {
return this._value;
}
masked(): string {
return this._value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}
equals(other: PhoneNumber): boolean {
if (!other) return false;
return this._value === other.value;
}
toString(): string {
return this.masked();
}
}