TanStackT
TanStack10mo ago
25 replies
excited-coffee

When is the schema validation ACTUALLY happening?

I encountered this issue - I have an age, that should be a number after submitting. However, to get it, I need to use TextField. Because of Typescript errors, I need to cast it as number (I know this isn't the best approach, but hear me out pls 😄 )

When I hit submit, the age value is run through the schema (which happens and logged REFINED VALUE is of type
number
). However, when I log the the value and its type in
onSubmit
handler, it is a
string
.

Isn't this weird? In zod, when I run values through a schema, I can count on them being the correct type, but here it seems it doesn't work that way. It seems like the result of the parsing is thrown away and the original values are returned in the
onSubmit
handler. Is this a bug or a required behavior?


const schema = z.object({
    age: z.coerce.number().min(18)
        .refine((val) => {
            console.log('REFINED VALUE: ', typeof val, val)
            return true
        })
})

type InputType = z.input<typeof schema>

const TanstackFormExample = () => {
    const defaultValues: InputType = {
        age: 12
    }

    const form = useForm({
        defaultValues,
        validators: {
            onSubmit: schema
        },
        onSubmit: ({ value }) => {
            console.log('ON SUBMIT: ', typeof value.age, value.age)
        }
    })

    return (
              ...
            <form.Field name='age'>
                {(field) => (
                    <TextInput
                        placeholder='Age'
                        value={field.state.value}
                        onChange={(e) => field.handleChange(e.target.value as unknown as number)}
                        onBlur={field.handleBlur}
                        error={field.state.meta.errors[0]?.message}
                    />
                )}
            </form.Field>
              ...
    )
}
Was this page helpful?