T
TanStack5mo ago
fair-rose

Conditionally rendered fields validation

Is there a better way to check validation for conditionally rendered fields? Here is an example of what I have got working:
const otherField = useStore(form.store, state => state.values.otherField)

{otherField && (
<form.Field
name="field"
validators={{
onSubmit: (value) => {
if (!form.state.values.otherField) {
return undefined;
}

// isNonNegativeFloat = some ZodNumber validation
const result = isNonNegativeFloat('field').safeParse(value.value);

if (result.success) {
return undefined;
}

return result.error.errors[0].message;
},
}}
/>
)}
const otherField = useStore(form.store, state => state.values.otherField)

{otherField && (
<form.Field
name="field"
validators={{
onSubmit: (value) => {
if (!form.state.values.otherField) {
return undefined;
}

// isNonNegativeFloat = some ZodNumber validation
const result = isNonNegativeFloat('field').safeParse(value.value);

if (result.success) {
return undefined;
}

return result.error.errors[0].message;
},
}}
/>
)}
This works but it's quite complicated, especially if you consider multiple layers of nesting e.g.
if (!form.store.state.values.otherField || form.store.state.values.otherFieldFalsy) {
return undefined;
}
if (!form.store.state.values.otherField || form.store.state.values.otherFieldFalsy) {
return undefined;
}
6 Replies
national-gold
national-gold5mo ago
you could implement zod‘s superRefine method for extra control
fair-rose
fair-roseOP5mo ago
I can give that a go, it was one I tried before but I found it just as complicated, in my personal opinion. Thanks! I will try it again
national-gold
national-gold5mo ago
refine is a simpler variant. Has too little control over the error type for my liking, but is much quicker and easier to use
fair-rose
fair-roseOP5mo ago
I understand you get a lot of control Honestly I would just love to do:
validators={{ onSubmit: otherField ? isNonNegativeFloatString('field') : undefined }}
validators={{ onSubmit: otherField ? isNonNegativeFloatString('field') : undefined }}
But doesn't seem to work.
national-gold
national-gold5mo ago
no, because you construct it once and that will be the set value so whatever otherField was at the beginning will be the result you‘d have to create a function that will check in its callback for the condition, safeParse the schema or return immediately
fair-rose
fair-roseOP5mo ago
Indeed, that's how I ended up with the current "working" solution. But still not ideal I guess superRefine is the best option, and perhaps moving towards a schema rather than on-field validation

Did you find this page helpful?