-
Notifications
You must be signed in to change notification settings - Fork 174
/
validators.ts
43 lines (34 loc) · 965 Bytes
/
validators.ts
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
41
42
43
export const validatePassword = (ctx: string, str: string) => {
if (typeof str !== 'string') {
throw TypeError(`${ctx} must be a string`);
}
validateLength(ctx, str, 8, 30);
if (!/[a-zA-Z]+/.test(str)) {
throw TypeError(`${ctx} must contain english letters`);
}
if (!/\d+/.test(str)) {
throw TypeError(`${ctx} must contain numbers`);
}
if (!/[^\da-zA-Z]+/.test(str)) {
throw TypeError(`${ctx} must contain special charachters`);
}
};
export const validateLength = (ctx: string, str: string, ...args: number[]) => {
let min, max;
if (args.length === 1) {
min = 0;
max = args[0];
} else {
min = args[0];
max = args[1];
}
if (typeof str !== 'string') {
throw TypeError(`${ctx} must be a string`);
}
if (str.length < min) {
throw TypeError(`${ctx} must be at least ${min} chars long`);
}
if (str.length > max) {
throw TypeError(`${ctx} must contain ${max} chars at most`);
}
};