-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.ts
68 lines (58 loc) · 1.67 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
62
63
64
65
66
67
68
import { z } from "zod";
export class ValidationError extends Error {
public name = "ValidationError";
public inner: Array<{ path: string; message: string }> = [];
public constructor(message: string) {
super(message);
}
}
function createValidationError(e: z.ZodError) {
const error = new ValidationError(e.message);
error.inner = e.errors.map((err) => ({
message: err.message,
path: err.path.join("."),
}));
return error;
}
/**
* Wrap your zod schema in this function when providing it to Formik's validation schema prop
* @param schema The zod schema
* @returns An object containing the `validate` method expected by Formik
*/
export function toFormikValidationSchema<T>(
schema: z.ZodSchema<T>,
params?: Partial<z.ParseParams>,
): { validate: (obj: T) => Promise<void> } {
return {
async validate(obj: T) {
try {
await schema.parseAsync(obj, params);
} catch (err: unknown) {
throw createValidationError(err as z.ZodError<T>);
}
},
};
}
function createValidationResult(error: z.ZodError) {
const result: Record<string, string> = {};
for (const x of error.errors) {
result[x.path.filter(Boolean).join(".")] = x.message;
}
return result;
}
/**
* Wrap your zod schema in this function when providing it to Formik's validate prop
* @param schema The zod schema
* @returns An validate function as expected by Formik
*/
export function toFormikValidate<T>(
schema: z.ZodSchema<T>,
params?: Partial<z.ParseParams>
) {
return async (values: T) => {
const result = await schema.safeParseAsync(values, params);
if (!result.success) {
return createValidationResult(result.error);
}
};
}