-
Notifications
You must be signed in to change notification settings - Fork 96
/
Validator.js
166 lines (146 loc) · 4.44 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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// linter resolves to the wrong file
// eslint-disable-next-line import/no-unresolved
import validator from 'validator';
import i18n from 'i18n';
/**
* Provides methods for handling client-side validation for Forms.
* Handles logic for repetitive validation tasks using a list of Form values and a given field or
* form schema, to determine if a field is valid.
*
* @class
*/
class Validator {
constructor(values) {
this.setValues(values);
}
setValues(values) {
this.values = values;
}
getFieldValue(name) {
let value = this.values[name];
if (typeof value !== 'string') {
// we'll consider it an empty value if it's false, undefined or null
if (typeof value === 'undefined' || value === null || value === false) {
value = '';
} else {
// CSVs the array by default, may look at doing something else for objects
value = value.toString();
}
}
return value;
}
validateValue(value, emptyValues, rule, config) {
// Empty values suppress error unless rule is required
if (emptyValues.includes(value)) {
return rule !== 'required';
}
switch (rule) {
case 'equals': {
const otherValue = this.getFieldValue(config.field);
return validator.equals(value, otherValue);
}
case 'numeric': {
return validator.isNumeric(value);
}
case 'date': {
return validator.isDate(value);
}
case 'alphanumeric': {
return validator.isAlphanumeric(value);
}
case 'alpha': {
return validator.isAlpha(value);
}
case 'regex': {
return validator.matches(value, config.pattern);
}
case 'max': {
return value.length <= config.length;
}
case 'email': {
return validator.isEmail(value);
}
default: {
// eslint-disable-next-line no-console
console.warn(`Unknown validation rule used: '${rule}'`);
return false;
}
}
}
/**
* Validates a give field schema with the values given in the instance.
*
* @param fieldSchema
* @returns {*}
*/
validateFieldSchema(fieldSchema) {
return this.validateField(
fieldSchema.name,
fieldSchema.validation,
fieldSchema.leftTitle !== null ? fieldSchema.leftTitle : fieldSchema.title,
fieldSchema.customValidationMessage
);
}
getMessage(rule, config) {
const name = config.title;
const message = (typeof config.message === 'string')
? config.message
: i18n._t(
`Admin.VALIDATOR_MESSAGE_${rule.toUpperCase()}`,
i18n._t('Admin.VALIDATOR_MESSAGE_DEFAULT', '{name} is not a valid value.')
);
return i18n.inject(message, { name });
}
/**
* Validates a field name with the values given in the instance.
*
* @param {string} name
* @param {object} rules
* @param {string} title
* @param {string} overrideMessage
* @returns {*}
*/
validateField(name, rules, title, overrideMessage) {
const response = { valid: true, errors: [] };
// no validation rules provided (possibly later), keep field as valid for now
if (!rules) {
return response;
}
const value = this.getFieldValue(name);
let emptyValues = [''];
if (rules.required && typeof rules.required === 'object' && rules.required.hasOwnProperty('extraEmptyValues')) {
emptyValues = emptyValues.concat(rules.required.extraEmptyValues);
}
// required rule given and empty value, so skip all other validation
if (rules.required && emptyValues.includes(value)) {
const config = Object.assign(
{ title: (title !== '') ? title : name },
rules.required
);
const message = overrideMessage || this.getMessage('required', config);
return {
valid: false,
errors: [message],
};
}
Object.entries(rules).forEach((ruleEntry) => {
const [rule, initConfig] = ruleEntry;
const config = Object.assign({ title: name }, { title }, initConfig);
// have done required above as priority
if (rule === 'required') {
return;
}
const valid = this.validateValue(value, emptyValues, rule, config);
if (!valid) {
const message = this.getMessage(rule, config);
response.valid = false;
response.errors.push(message);
}
});
if (overrideMessage && !response.valid) {
response.errors = [overrideMessage];
}
return response;
}
}
export default Validator;