Form.constants.ts17 lines · main
1import * as z from 'zod'
2
3export const StringNumberOrNull = z
4 .string()
5 .transform((v) => (v === '' ? null : v))
6 .nullable()
7 .refine((value) => value === null || !isNaN(Number(value)), {
8 message: 'Invalid number',
9 })
10 .transform((value) => (value === null ? null : Number(value)))
11
12/**
13 * [Joshen] After wrangling with RHF I think this is the easiest way to handle nullable number fields
14 * - Declare the field normally as you would in the zod form schema (e.g field: z.number().nullable())
15 * - In the InputField, add a form.register call `{...form.register('field_name', { setValueAs: setValueAsNullableNumber })}`
16 */
17export const setValueAsNullableNumber = (v: any) => (v === '' || v === null ? null : parseInt(v))