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