-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.ts
236 lines (206 loc) · 7.12 KB
/
validate.ts
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import {
DEFAULT_VALIDATION_ERROR_MESSAGE,
ErrorMessageFunction,
GlobalValidators,
InputValidationByKey,
InputValidationConfig,
ValidatorFunction,
ValidatorFunctionOptions
} from './formalizer';
import { ValidationResult } from './use-form-input';
// apparently can't import a type from an optional dependency, so use "any" until this is resolved.
// https://stackoverflow.com/questions/52795354/how-to-use-a-type-from-an-optional-dependency-in-a-declaration-file
// https://stackoverflow.com/questions/55041919/import-of-optional-module-with-type-information
let validator: any = void 0;
const loadValidatorDependency = () => {
validator = require('validator');
if (validator !== undefined) {
return true;
}
const validatorVersion: string | undefined = require('validator/package.json')
.version;
// check if we support the validator version - throw error if unsupported
if (validatorVersion) {
const versionParts = validatorVersion.split('.');
if (parseInt(versionParts[0], 10) < 4) {
// major version is 11 or higher
validator = undefined;
throw new Error(
`Formalizer: unsupported version of the validator library found (${validatorVersion}). Please upgrade to 4.0.0 or higher.`
);
}
}
return validator !== undefined;
};
const getErrorMessage = <T>(
errorMsg: string | ErrorMessageFunction<T> | undefined,
value: string,
formData: T
) => {
if (typeof errorMsg === 'string') {
return errorMsg;
} else if (typeof errorMsg === 'function') {
return errorMsg(value, formData);
} else {
throw new Error(
`Formalizer: a validator's errorMessage field must be either a string or a function that returns a string.`
);
}
};
/**
* Returns either unmet rule, or null
* @param value
* @param validation
* @returns {*}
*/
export const validate = <T>(
value: any,
validation: InputValidationByKey<T>,
formData: T
): ValidationResult => {
const result: ValidationResult = {
errors: []
};
const fieldsToValidate: Array<InputValidationConfig<T>> = [];
Object.keys(validation).forEach(property => {
let options = { formData };
let errorMsg: string = DEFAULT_VALIDATION_ERROR_MESSAGE;
let negate: boolean | undefined = false;
let validatorFunction: ValidatorFunction<T> | undefined = void 0;
if (GlobalValidators[property]) {
// making sure the given validator is of supported type
if (
GlobalValidators[property] === null ||
(typeof GlobalValidators[property] !== 'string' &&
typeof GlobalValidators[property] !== 'object') ||
Array.isArray(GlobalValidators[property])
) {
throw new Error(
'Formalizer: validators must be of string or object type.'
);
}
if (typeof GlobalValidators[property] === 'string') {
if (loadValidatorDependency()) {
// @ts-ignore
validatorFunction = validator[
GlobalValidators[property] as string
] as ValidatorFunction<T>;
}
errorMsg = GlobalValidators[property] as string;
negate = false;
} else {
// can only be an object at this point
const propValidator = GlobalValidators[
property
] as InputValidationConfig<T>;
if (typeof propValidator.validator === 'string') {
if (loadValidatorDependency()) {
validatorFunction = validator[propValidator.validator];
}
} else if (typeof propValidator.validator === 'function') {
validatorFunction = propValidator.validator;
} else {
throw new Error(
'Formalizer: the given validator must be either a string or a function.'
);
}
if (propValidator.errorMessage) {
errorMsg = getErrorMessage(
propValidator.errorMessage,
value,
formData
);
}
negate = propValidator.negate === void 0 ? false : propValidator.negate;
options =
propValidator.options === void 0
? { formData }
: (propValidator.options as ValidatorFunctionOptions<T>);
}
} else {
const valConfig = validation[property] as InputValidationConfig<T>;
// if this is an empty object, user passed in just the string for a built in validator, which got converted to an
// empty object before validate was invoked.
if (Object.keys(valConfig as object).length === 0) {
if (loadValidatorDependency()) {
validatorFunction = (validator as any)[property];
}
} else if (typeof valConfig.validator === 'function') {
validatorFunction = valConfig.validator;
} else if (
typeof valConfig === 'object' &&
typeof valConfig.validator === 'string'
) {
if (loadValidatorDependency()) {
validatorFunction = validator[valConfig.validator];
}
}
}
fieldsToValidate.push({
errorMessage: errorMsg,
key: property,
negate,
options,
validator: validatorFunction
});
fieldsToValidate[fieldsToValidate.length - 1] = {
...fieldsToValidate[fieldsToValidate.length - 1],
...(validation[property] as object)
};
// making sure the resolved function is used
fieldsToValidate[fieldsToValidate.length - 1].validator = validatorFunction;
});
let unmetValidationKey: string | undefined = void 0;
let errorMessage: string | ErrorMessageFunction<T> | undefined = void 0;
for (const validationConfig of fieldsToValidate) {
let isValid = true;
let validationResult;
const property = validationConfig.key;
const configs: InputValidationConfig<T> = validationConfig;
if (!configs.options) {
configs.options = { formData };
} else if (!configs.options.formData) {
configs.options = { ...configs.options, formData };
}
switch (property) {
case 'isRequired':
if (!value || value.trim().length === 0) {
isValid = false;
}
break;
default:
if (typeof configs.validator === 'function') {
validationResult = configs.validator(
value,
configs.options as ValidatorFunctionOptions<T>
);
if (typeof validationResult === 'boolean') {
isValid = validationResult;
} else if (typeof validationResult === 'string') {
isValid = false;
}
} else {
throw new Error(
`Formalizer: cannot find a validator named "${property}". If you are attempting to perform a validation defined ` +
`by the Validator library, please make sure to have it installed prior.`
);
}
}
if (configs.negate) {
isValid = !isValid;
}
if (property) {
if (!isValid) {
unmetValidationKey = property;
errorMessage =
typeof validationResult === 'string'
? validationResult
: getErrorMessage(validationConfig.errorMessage, value, formData);
result.errors.push({ key: unmetValidationKey, errorMessage });
} else {
result.errors.push({ key: property });
}
}
}
return result;
};