This repository was archived by the owner on Mar 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschema.js
73 lines (66 loc) · 1.99 KB
/
schema.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*!
*
* Copyright(c) 2023 Mark Maher Ewida(Marco5dev)
* MIT Licensed
*/
"use strict";
class Schema {
constructor(fields) {
this.fields = fields;
}
validate(data) {
const errors = {};
for (const field in this.fields) {
const fieldConfig = this.fields[field];
const fieldType = fieldConfig.type;
const value = data[field];
if (fieldConfig.required && (value === undefined || value === null)) {
errors[field] = "This field is required.";
} else if (fieldType === "string" && typeof value !== "string") {
errors[field] = `Invalid type. Expected String, got ${typeof value}.`;
} else if (fieldType === "number" && typeof value !== "number") {
errors[field] = `Invalid type. Expected Number, got ${typeof value}.`;
} else if (
fieldType.type === "string" &&
fieldType.minlength &&
value.length < fieldType.minlength
) {
errors[
field
] = `Invalid length. Minimum length is ${fieldType.minlength}.`;
} else if (
fieldType.type === "string" &&
fieldType.maxlength &&
value.length > fieldType.maxlength
) {
errors[
field
] = `Invalid length. Maximum length is ${fieldType.maxlength}.`;
} else if (
fieldType.type === "number" &&
fieldType.min &&
value < fieldType.min
) {
errors[
field
] = `Value should be greater than or equal to ${fieldType.min}.`;
} else if (
fieldType.type === "number" &&
fieldType.max &&
value > fieldType.max
) {
errors[
field
] = `Value should be less than or equal to ${fieldType.max}.`;
} else if (
fieldType.validate &&
typeof fieldType.validate === "function" &&
!fieldType.validate(value)
) {
errors[field] = "Invalid value.";
}
}
return Object.keys(errors).length === 0 ? null : errors;
}
}
module.exports = Schema;