-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform-validator.js
40 lines (37 loc) · 1.21 KB
/
form-validator.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
function FormValidator(form) {
this.form = form;
this.errors = [];
this.validators = [];
this.allowEmptyInput = false;
}
FormValidator.prototype.registerValidator = function (querySelector, errorType, errorMessage) {
this.validators.push({
querySelector: querySelector,
errorMessage: errorMessage,
errorType: errorType
})
}
FormValidator.prototype.validateForm = function (validator) {
let errors = [];
let nodeList = this.form.querySelectorAll(validator.querySelector);
for (let i = 0; i < nodeList.length; i++) {
const element = nodeList[i];
const invalid = element.validity[validator.errorType];
const empty = !this.allowEmptyInput && !element.value.trim();
if (invalid || empty) {
errors.push({
element: element,
message: validator.errorMessage(element.name)
})
}
}
this.errors = this.errors.concat(errors);
}
FormValidator.prototype.validate = function () {
this.errors = [];
for (let v = 0; v < this.validators.length; v++) {
const validator = this.validators[v];
this.validateForm(validator);
}
return this.errors.length ? false : true;
}