T
TanStack10mo ago
harsh-harlequin

Change validation type after initial validation

Hi! Is there a way I can configure my form to have the initial validation occur on form submission and when the form has been submitted once, the validations should occur onChange? This is a thing I'm missing from this library compared to RHF. Cheers 🖐️
4 Replies
statutory-emerald
statutory-emerald10mo ago
I don't think we have an internal api to do that, but you could for sure handle a flag manually. You set it true in the onSubmit and you use it to toggle between validators
harsh-harlequin
harsh-harlequinOP10mo ago
Solved it like this.
const isFormSubmitted =form.useStore((state) => state.submissionAttempts) > 0;
const validatorKey: keyof FieldValidators<unknown, string> = isFormSubmitted
? "onChange"
: "onSubmit";

...

<form.Field
name="email"
validators={{
[validatorKey]: z.string().email("Invalid email address."),
}}
>
const isFormSubmitted =form.useStore((state) => state.submissionAttempts) > 0;
const validatorKey: keyof FieldValidators<unknown, string> = isFormSubmitted
? "onChange"
: "onSubmit";

...

<form.Field
name="email"
validators={{
[validatorKey]: z.string().email("Invalid email address."),
}}
>
statutory-emerald
statutory-emerald10mo ago
That counter goes up even if submission is invalid but if it's ok in your scenario that's indeed a nice way to handle that. Good catch 🙂
harsh-harlequin
harsh-harlequinOP10mo ago
Yes, that is exactly what I'm looking for 🙂

Did you find this page helpful?