-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmail.ts
More file actions
40 lines (31 loc) · 833 Bytes
/
Email.ts
File metadata and controls
40 lines (31 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export class Email extends String {
private static readonly PATTERN =
/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
constructor(value: any) {
if (typeof value !== 'string') {
throw new TypeError(`Email: expected string, got ${value.constructor}`);
}
const normalized = value.trim().toLowerCase();
if (!Email.PATTERN.test(normalized)) {
throw new TypeError(`Email: invalid address "${value}"`);
}
super(value)
}
get local(): string {
return this.split('@')[0];
}
get domain(): string {
return this.split('@')[1];
}
equals(other: Email): boolean {
return this.toString() === other.toString();
}
static isValid(value: unknown): boolean {
try {
new Email(value as string);
return true;
} catch {
return false;
}
}
}