T
TanStack2mo ago
conscious-sapphire

useFieldContext

I have created a InputField component, but I need to extend the label for an input which tells me if a input is optional. Is there a way I can check whether or not a field is optional based on field.state (or something like that)?. I use zod as a validation schema.
7 Replies
multiple-amethyst
multiple-amethyst2mo ago
you would need access to meta properties of the schema, which standard schema v1 does not expose. Perhaps this changes in a future spec, but for now, you‘ll need to manually pass the required info
conscious-sapphire
conscious-sapphireOP2mo ago
I cannot see a "isRequired" like property in the meta properties. Do I need to create my own for now?
multiple-amethyst
multiple-amethyst2mo ago
hmmm … I remember seeing some „nullable“ prop in the zod schema‘s shape perhaps required doesn‘t exist, but nonnullable and nonoptional can be checked for schema.isOptional()
multiple-amethyst
multiple-amethyst2mo ago
No description
automatic-azure
automatic-azure2mo ago
The suggestion from the deprecation-message seems interesting.
schema.safeParse(undefined).success
schema.safeParse(undefined).success
if that works you could put that into a helper function to make the intend clearer
isFieldRequired(fieldSchema)
isFieldRequired(fieldSchema)
conscious-sapphire
conscious-sapphireOP2mo ago
Thanks! That's a good approach. The only "problem" with this approach is that I cannot infere this in the global field-components. Would be nice to apply it directly InputField. Maybe I can get the schema from form store or something... hmm
multiple-amethyst
multiple-amethyst2mo ago
sort of. You can, but not in a type safe way. field.form is the form calling the field component, and the form contains options which includes validators that were passed to it but you then need to extract your field-specific shape if the validator exists

Did you find this page helpful?