TanStackT
TanStack10mo ago
18 replies
excited-coffee

Optional fields

Hi guys, I have a question about Tanstack Form.
const schema = z.object({
    name: z.string().min(2, 'Name must be at least 2 characters long'),
    email: z.string().email('Invalid email address').optional(),
    age: z.coerce.number().min(18, 'You must be at least 18 years old')
})

const TanstackFormExample = () => {
    const form = useForm({
        defaultValues: {
            name: '',
            email: '',
            age: 12
        },
        validators: {
            onChange: schema
        },
        onSubmit: ({ value }) => {
            console.log(value)
        }
    })

You can see that email is optional. But when I do it like this, the line onChange: schema starts firing an error sayng The types of ''~standard'.types' are incompatible between these types.. What is the best approach to handle optional fields?

Someone suggested casting the default values like this:
        defaultValues: {
            name: '',
            email: undefined,
            age: 12
        } as z.input<typeof schema>,


But I don't really like casting and I feel like there should be a nicer solution to have some fields optional
Was this page helpful?