Using methods / schemas / actions in check()
Hi !
I recently came across this issue because I encountered a similar situation :
@fabian-hiller is it somehow possible to use methods / schemas / actions after the partial check? For instance — I have a form field that can be nullable, and if it’s not null, I want to perform some complex validations on it — it seems that I’m on my own once I’m inside the forward method, and can’t make use of any valibot methods / schemas / actions
Originally posted by @selrond in #645
When doing complex conditional validation on an object, using manual conditions can become tedious. You can get around this by calling safeParse inside check():
const schema = v.pipe(
v.object({
a: v.string(),
b: v.array(v.string()),
}),
v.forward(
v.check(({ a, b }) => {
if (["foo", "bar"].includes(a)) {
// Would be a more complex validation in a real-world scenario
return v.safeParse(v.pipe(v.array(v.string()), v.minLength(1)), b).success;
}
return true;
}, "b must contain at least one element"),
["b"],
),
);But what bothers me most about this approach is that I lose the error generated by safeParse. I have to rewrite the error message as the second argument to check. That's really what I find unfortunate.
So I wondered if we could tweak the API a bit so that check would accept a requirement argument that could be either a boolean or a BaseSchema.
requirement (input: TInput) => boolean | BaseSchema
const schema = v.pipe(
v.object({
a: v.string(),
b: v.array(v.string()),
}),
v.forward(
v.check(({ a, b }) => {
if (["foo", "bar"].includes(a)) {
return v.pipe(v.array(v.string()), v.minLength(1));
}
return true;
}, /* No need for an error message here */),
["b"],
),
);The only problem I see with this is determining which fields to apply the validation to.
So, that's my two cents on this amazing library I discovered not long ago. I think it would make Valibot even more powerful; I think it's a shame to have to fall back on manual validation in cases like this.
Source: open-circle/valibot