Form.constants.ts 734 B

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