-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormValidator.js
More file actions
123 lines (97 loc) · 2.23 KB
/
FormValidator.js
File metadata and controls
123 lines (97 loc) · 2.23 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import { Validatinator } from "validatinator";
export class FormValidator {
#config;
#messages;
#formSelector;
#fields;
#errors = {};
#valid = false;
#results = {};
#validator;
constructor(config, msgs) {
const hasNewMessages = msgs && Object.keys(msgs).length > 0;
if (hasNewMessages) {
this.#validator = new Validatinator(config, msgs);
this.#messages = msgs;
} else {
this.#validator = new Validatinator(config);
}
this.#config = config;
this.#formSelector = Object.keys(this.#config)[0];
this.#fields = Object.keys(this.config[this.formSelector]);
}
get config() {
return this.#config;
}
set config(config) {
this.#config = config;
}
get errors() {
return this.#errors;
}
set errors(errors) {
this.#errors = errors;
}
get valid() {
return this.#valid;
}
set valid(valid) {
this.#valid = valid;
}
get results() {
return this.#results;
}
set results(results) {
this.#results = results;
}
get validator() {
return this.#validator;
}
set validator(validator) {
this.#validator = validator;
}
get formSelector() {
return this.#formSelector;
}
set formSelector(formSelector) {
this.#formSelector = formSelector;
}
get fields() {
return this.#fields;
}
set fields(fields) {
this.#fields = fields;
}
get messages() {
return this.#messages;
}
set messages(messages) {
this.#messages = messages;
}
getErrors(state) {
const errors = {};
this.#fields.forEach((field) => {
errors[field] = state.getFieldErrors(field);
});
return errors;
}
getCampoError(campo) {
return this.validator.getFieldErrors(campo);
}
async validate() {
const state = await this.validator.validate(this.#formSelector);
const ERRORS = this.getErrors(state);
const VALID = Object.values(ERRORS).every((error) => error.length === 0);
const NEW_STATE = {
fieldsConfiguration: state.formFieldConfigs,
results: state.results,
errors: ERRORS,
valid: VALID,
invalid: !VALID,
};
this.#errors = NEW_STATE.errors;
this.#results = NEW_STATE.results;
this.#valid = NEW_STATE.valid;
return NEW_STATE;
}
}