-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (88 loc) · 3.1 KB
/
index.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
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
import commonRules from './validatorRules/commonRules';
const importRules = {
...commonRules
};
/**
* @class
*/
class Validator {
constructor(rules = {}) {
this.rules = {
...importRules,
...rules
};
}
chainValidation = (option, value) => {
const error = option.name
? this.rules[option.name](value, option)
: this.rules[option](value);
if (error) {
this.buildResults(error);
} else if (option.next) {
this.chainValidation(option.next, value);
}
};
/**
* Provide validation to value param
* @param {string} value - String to validate
* @param {Array} options - array of strings or objects(if rule requires additional params) rules
* @return {{results: {}, valid: boolean}}
* @desc results is a composition of name - error message of rules which failed during validation process
*/
validate(value = '', options) {
this.errorObject = {
results: {},
valid: true
};
options.forEach(option => {
this.chainValidation(option, value);
});
return this.errorObject;
}
/**
* Provide validation to group of values
* @param {Array} data - array of objects to validate with keys field, data, rules
* @return {{valid: boolean, errorObjects: Object}}
*/
validateGroup(data) {
const errorObjects = data.reduce((result, validationProps) => ({
...result,
[validationProps.field || validationProps.data || 'no_value_provided']: this.validate(validationProps.data || '', validationProps.rules)
}), {});
const valid = Object.values(errorObjects).every((checkResult) => checkResult.valid);
return { valid, errorObjects };
}
addRegExpRule(name, rules, errorMsg) {
this.rules[name] = val => {
if (Array.isArray(rules)) {
rules.forEach((rule) => {
if (!rule.test(val)) {
this.buildResults({ [name]: errorMsg });
}
});
} else if (!rules.test(val)) {
this.buildResults({ [name]: errorMsg });
}
};
}
/**
* @param {string} name - new rule name (should be passed with this name in 'validate' method)
* @param {function} rule - depending on this param return value current validation will be failed(return false) or resolved (returns true)
* @param {string} errorMsg - message to show in errors object about current rule if it fails (e.g. 'cannot be empty')
*/
addRule(name, rule, errorMsg) {
this.rules[name] = (val, options) => {
const rulecheck = !rule(val, options);
return rulecheck && { [name]: errorMsg instanceof Function ? errorMsg(val, options) : errorMsg };
};
return this;
}
buildResults(error) {
this.errorObject.results = {
...this.errorObject.results,
...error
};
this.errorObject.valid = false;
}
}
export default Validator;