-
Notifications
You must be signed in to change notification settings - Fork 0
/
Validator.js
72 lines (64 loc) · 1.47 KB
/
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
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
export default class Validator {
constructor(defaultMessage) {
this.defaultMessage = defaultMessage;
this.message = '';
this.steps = [];
this.failed = false;
}
/**
* Return the index of step, if exists.
* @param {*} name
*/
_stepExists(name) {
for (var i = 0; i < this.steps.length; i++) {
if (this.steps[i].name == name) {
return i;
}
}
return false;
}
addStep(name, callback, message) {
const stepExists = this._stepExists(name);
if (stepExists !== false){
this.steps.splice(stepExists, 1)
}
this.steps.push({ name, callback, message });
}
required(message) {
this.addStep(
'required',
v => {
if (typeof v === 'undefined') return false;
if (v === null) return false;
if (String(v) == '') return false;
return true;
},
message
);
return this;
}
run(value) {
this.failed = false;
for (let i = 0; i < this.steps.length; i++) {
if (!this.steps[i].callback(value)) {
return this.fail(this.steps[i].message);
}
}
return true;
}
fail(message) {
this.failed = true;
this.setMessage(message);
return false;
}
setMessage(message) {
this.message = message;
}
getMessage() {
if (this.message && this.message != '') {
return this.message;
} else {
return this.defaultMessage;
}
}
}