-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
42 lines (36 loc) · 895 Bytes
/
validate.js
File metadata and controls
42 lines (36 loc) · 895 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
41
42
export function validate(schema, data) {
const errors = {}
const clean = {}
for (const key in schema) {
const rules = schema[key]
const value = data[key]
if (
rules.required &&
(value === undefined || value === null || value === "")
) {
errors[key] = `${key} is required`
continue
}
const customError = rules.validate(value)
if (customError) {
errors[key] = customError
continue
}
// Store validated value (trimmed if string)
clean[key] = typeof value === "string" ? value.trim() : value
}
return {
isValid: Object.keys(errors).length === 0,
errors,
clean
}
}
export function escapeHtml(str) {
if (typeof str !== "string") return ""
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
}