Accessing zod's custom issue params #2013
Replies: 1 comment
-
|
Unfortunately, TanStack Form's error type is just Here are a couple of ways to work around this: Option 1: Encode the error type in the message string The simplest approach — use a structured message format you can parse on the field side: // In your Zod schema
ctx.addIssue({
code: 'custom',
message: JSON.stringify({ text: 'Duplicate detected', type: 'FORCE_BYPASS' }),
path: ['field'],
})// In your field component
<form.Field name="field">
{(field) => {
const errorData = field.state.meta.errors
.filter(Boolean)
.map((err) => {
try { return JSON.parse(err) }
catch { return { text: err, type: 'default' } }
})
return (
<>
<input
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
{errorData.map((err, i) => (
<div key={i}>
<span>{err.text}</span>
{err.type === 'FORCE_BYPASS' && (
<label>
<input type="checkbox" onChange={handleForceBypass} />
Force override
</label>
)}
</div>
))}
</>
)
}}
</form.Field>Option 2: Use a field-level validator instead of Zod for this specific field Return a structured object from a custom validator. TanStack Form validators can return any type, not just strings: <form.Field
name="field"
validators={{
onChange: ({ value }) => {
if (isDuplicate(value)) {
return { message: 'Duplicate detected', errorType: 'FORCE_BYPASS' }
}
if (!value) {
return { message: 'Required', errorType: 'default' }
}
return undefined
},
}}
>
{(field) => {
const errors = field.state.meta.errors.filter(Boolean)
return (
<>
<input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />
{errors.map((err: any, i) => (
<div key={i}>
{err.message}
{err.errorType === 'FORCE_BYPASS' && <ForceCheckbox />}
</div>
))}
</>
)
}}
</form.Field>Option 3: Side-channel state Use a separate piece of state (e.g., a I'd go with Option 2 for the cleanest result — TanStack Form's native validators are more flexible than Zod for this kind of UI-aware error handling. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a zod schema applied on the useForm hook as a dynamic validator, with superRefine that adds a custom issue as follows:
ctx.AddIssue({ code: 'custom', message: 'Error message', path: ['field'], params: { myCustomErrorType: 1 }})Is there any way to access the
paramsobject on the field's meta?Use case:
I have a field that could cause a number of different errors and, based on the error type, frontend should render different components (for example, a "Force" checkbox to bypass validation on myCustomErrorType === 1)
Hope it's clear. Thanks in advance for any guidance!
Beta Was this translation helpful? Give feedback.
All reactions