I created a function to validate FormData objects with Zod, using a generic type for flexibility across schemas.
Here's the validate
function:
export function validate<T>(
formData: FormData,
schema: z.ZodSchema<T>
): { validatedData: T; errors: null } | { validatedData: null; errors: ActionErrors<T> } {
const body = parseFormData(formData);
const validated = schema.safeParse(body);
if (!validated.success) {
return {
validatedData: null,
errors: formatZodErrors<T>(validated.error),
};
}
return { validatedData: validated.data, errors: null };
}
The issue is that the properties in schemas with default values set are being treated as optional when using the helper function.
For example, here is the schema used in the validate
function:
export const createUserSchema = z.object({
name: fullName(),
email: email(),
sendActivationEmail: z.boolean().default(true)
});
Intellisense indicates the property as optional
This behavior of returning optional properties doesn't seem logical. Any insights or assistance would be highly appreciated 😊.
It's worth mentioning that skipping the helper function and parsing the data directly in the action does not result in optional properties as expected.