TanStackT
TanStack9mo ago
20 replies
urgent-maroon

Complex object Select field, no reasonable defaultValue, and validation

I've got a "Create equipment" form. It's got 2 required selections, which will determine relations with other data. There's a "model" for selecting the equipment model relation, and a "customer" for selecting the customer who owns this instance of that model.
Both of the selectors result in field values that are complex object.

            <form.AppField
              name="model"
              validators={{
                onBlur: equipmentFormDataSchema().shape.model,  // this doesn't type check
              }}
              children={(field) => {
                return <field.ModelSelectorField label="Model" />;
              }}
            />


The equipmentFormDataSchema is defined as
// A "selectable object" is a schema for fields that are populated as a subschema
// object by a Select; in this case, we don't want all of the subschema errors,
// we just want to know when a selection got skipped.
const selectableObject = <T extends z.ZodTypeAny>(schema: T, message: string) =>
  schema
    .optional()
    .catch(undefined)
    .refine((x) => !!x, { message });

const equipmentFormDataSchema = (
  required_error: string = "Equipment selection is required",
) =>
  z.object(
    {
      serialNumberOrVIN: z
        .string({ required_error: "Serial number or VIN is required" })
        .nonempty("Serial number or VIN is required"),
      plateNumber: z.string().nullish(),
      carNumber: z.string().nullish(),
      notes: z.string().nullish(),
      model: selectableObject(equipmentModelFormDataSchema(), "Model selection is required"),
      customer: selectableObject(customerFormDataSchema(), "Customer selection is required"),
    },
    { required_error },
  );


All of this mostly accomplishes what I want, but it leaves me with a Typescript error on the onBlur.

I'm not sure whether my issue has more to do with failing to understand my requirements, or how to apply Zod to those, or how to combine the Zod validator with TSF.
Was this page helpful?