-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
61 lines (51 loc) · 1.76 KB
/
index.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
import 'reflect-metadata';
import { transformAndValidateSync } from 'class-transformer-validator';
import { ValidationError, ValidationOptions } from 'class-validator';
import { values, size } from 'lodash';
import { Type, TypeHelpOptions } from 'class-transformer';
import { ValidateNested as OriginalValidateNested, registerDecorator, ValidationArguments } from 'class-validator';
export * from 'class-validator';
export const ValidateNested = (typeFunction: (type?: TypeHelpOptions) => Function, options: ValidationOptions) =>
(target: any, key: string) => {
OriginalValidateNested(options)(target, key);
Type(typeFunction)(target, key);
}
export { TypeHelpOptions };
function convertErrorToFormikFormat(errors: Array<ValidationError>) {
const result = {};
for (const error of Array.from(errors)) {
result[error.property] = values(error.constraints)[0];
if (size(error.children) > 0) {
result[error.property] = convertErrorToFormikFormat(error.children);
}
}
return result;
}
export const formikValidate = (modelClass, data) => {
try {
transformAndValidateSync(modelClass, data);
return {};
} catch (e) {
return convertErrorToFormikFormat(e);
}
}
export class FormikValidatorBase {
static createValidator() {
return data => formikValidate(this, data);
}
}
export function ValidateWith(validate: (args: ValidationArguments) => boolean, validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
return validate(args);
}
}
});
};
}