1 import i18next from "i18next";
2 import { FieldPath, FieldValues, UseFormReturn } from "react-hook-form";
3 import { z } from "zod";
4
5 /**
6 * Helper function to cast a z.union([z.number(), z.string()]) to a number
7 */
8 export const castNumber = (number: number | string) => {
9 return typeof number === "string" ? Number(number.replace(",", ".")) : number;
10 };
11
12 /**
13 * Validates that an optional value is an integer.
14 */
15 export const optionalInt = z
16 .union([z.string(), z.number()])
17 .optional()
18 .refine(
19 (value) => {
20 if (value === "" || value === undefined) {
21 return true;
22 }
23
24 return Number.isInteger(castNumber(value));
25 },
26 {
27 error: i18next.t("validation.mustBeInt"),
28 }
29 )
30 .refine(
31 (value) => {
32 if (value === "" || value === undefined) {
33 return true;
34 }
35
36 return castNumber(value) >= 0;
37 },
38 {
39 error: i18next.t("validation.mustBePositive"),
40 }
41 );
42
43 /**
44 * Validates that an optional value is an number.
45 */
46 export const optionalFloat = z
47 .union([z.string(), z.number()])
48 .optional()
49 .refine(
50 (value) => {
51 if (value === "" || value === undefined) {
52 return true;
53 }
54
55 return castNumber(value) >= 0;
56 },
57 {
58 error: i18next.t("validation.mustBePositive"),
59 }
60 );
61
62 /**
63 * Schema for metadata form.
64 */
65 export const metadataFormSchema = z.array(
66 z.object({
67 key: z.string(),
68 value: z.unknown(),
69 isInitial: z.boolean().optional(),
70 isDeleted: z.boolean().optional(),
71 isIgnored: z.boolean().optional(),
72 })
73 );
74
75 /**
76 * Validate subset of form fields
77 * @param form
78 * @param fields
79 * @param schema
80 */
81 export function partialFormValidation<TForm extends FieldValues>(
82 form: UseFormReturn<TForm>,
83 fields: FieldPath<any>[],
84 schema: z.ZodSchema<any>
85 ) {
86 form.clearErrors(fields as any);
87
88 const values = fields.reduce((acc, key) => {
89 acc[key] = form.getValues(key as any);
90 return acc;
91 }, {} as Record<string, unknown>);
92
93 const validationResult = schema.safeParse(values);
94
95 if (!validationResult.success) {
96 validationResult.error.issues.forEach((issue) => {
97 form.setError(issue.path.join(".") as any, {
98 type: issue.code,
99 message: issue.message,
100 });
101 });
102
103 return false;
104 }
105
106 return true;
107 }