-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
30 lines (30 loc) · 841 Bytes
/
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
import Joi, { AsyncValidationOptions } from "joi";
export class ValidationError extends Error {
public name = "ValidationError";
public inner: Array<{ path: string; message: string }> = [];
public constructor(message: string) {
super(message);
}
}
function createErrorSchema(e: Joi.ValidationError) {
const error = new ValidationError(e.message);
error.inner = e.details.map((err) => ({
message: err.message,
path: err.path.join(".")
}));
return error;
}
export function joiFormikAdapter<T>(
schema: Joi.ObjectSchema,
options: AsyncValidationOptions = { abortEarly: false, allowUnknown: true }
) {
return {
async validate(obj: T) {
try {
await schema.validateAsync(obj, options);
} catch (err: any) {
throw createErrorSchema(err as Joi.ValidationError);
}
}
};
}