How to conditionally require a field? #297
-
Hi, I have a field that should be required conditionally, depending on a checkbox outside of the form. How can I implement that with Valibot?
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 12 replies
-
There are several solutions. To make it type safe, I recommend using a discriminated union with |
Beta Was this translation helpful? Give feedback.
-
@fabian-hiller I'll continue here ok? This is how I solved this problem, variant and union didn't help import * as v from 'valibot';
export const schema1 = v.object({
name: v.pipe(
v.string(),
v.trim(),
v.nonEmpty(),
),
});
/*
// This won't work
const schema2 = v.object({
supplier: v.picklist(['JS', 'GO']),
ecmaVersion: v.union(
[v.null(), v.string()],
[v.check((input) = input.supplier !== 'JS', 'ecmaVersion required'],
),
});
*/
export const schema2 = v.pipe(
v.object({
supplier: v.picklist(['JS', 'GO']),
ecmaVersion: v.optional(v.string())
}),
v.forward(
v.check((input) => input.supplier !== 'JS', 'ecmaVersion required'),
['ecmaVersion']
)
)
// This won't work
// const Schema = v.object({
// ...schema1.entries,
// ...schema2.entries,
// });
const Schema = v.intersect([
schema1,
schema2,
]);
const result = v.safeParse(Schema, {
name: 'Some name',
supplier: 'JS',
recurrence: undefined,
});
console.log(result); |
Beta Was this translation helpful? Give feedback.
I recommend to write the following.
union
has nopipe
argument yet, that's why I added the validation toobject
and forwarded the error toname
. I plan to improve that.