-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicValidator.ts
More file actions
52 lines (44 loc) · 1.38 KB
/
basicValidator.ts
File metadata and controls
52 lines (44 loc) · 1.38 KB
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
44
45
46
47
48
49
50
51
52
import { CustomValidator } from "./types.ts"
export const isString: CustomValidator = {
validator: (value) => typeof value === "string", message: "Not a string"
}
export const isNumber: CustomValidator = {
validator: (value) => typeof value === "number", message: "Not a number"
}
export function length(min: number, max?: number): CustomValidator {
return {
validator: (value) => {
if (value.toString().length < min) {
return false
}
if (max && value.toString().length > max) {
return false
}
return true;
},
message: `Value length must be greater than ${min}${max ? `, less than ${max}` : ""}`
}
}
export const isEmail: CustomValidator = {
validator: (value) => /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value), message: "Invalid email address"
}
export function isArrayOf(customValidator?: CustomValidator): CustomValidator {
let errorMessage = "Not an array";
return {
validator: (value) => {
if (!Array.isArray(value)) {
return false;
}
if (customValidator) {
for (const v of value) {
if (!customValidator.validator(v)) {
errorMessage = (typeof customValidator.message === "function" ? customValidator.message() : customValidator.message)
return false;
}
}
}
return true;
},
message: () => errorMessage
}
}