Is conditional generation of pipes possible? #1029
-
I have some schema of the form in json (from backend), from which I generate the form markup itself and want to use this schema for validation via valibot. // Part of form schema
const fieldOpts = {
type: 'string',
minLength: 4,
} To do this, I conditionally add validators to the array and then pass them to const rules: Parameters<typeof v.pipe>[1][] = []
if (fieldOpts.type === 'string')
rules.push(v.string())
if (fieldOpts.minLength)
rules.push(v.minLength(fieldOpts.minLength))
const Schema = v.pipe(...rules) It works, but I get type errors. So, how to fix the types and is it even possible to use Thank you in advance! |
Beta Was this translation helpful? Give feedback.
Answered by
fabian-hiller
Jan 23, 2025
Replies: 1 comment 2 replies
-
Yes, something like this is possible. Here is a playground. import * as v from 'valibot';
// Part of form schema
const fieldOpts = {
type: 'string',
minLength: 4,
};
let Schema: v.GenericSchema | null = null;
if (fieldOpts.type === 'string') {
const rules: v.PipeItem<string, string, v.BaseIssue<unknown>>[] = [];
if (fieldOpts.minLength) rules.push(v.minLength(fieldOpts.minLength));
Schema = v.pipe(v.string(), ...rules);
}
if (Schema) {
const result = v.safeParse(Schema, 'example');
console.log(result);
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
ceigh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, something like this is possible. Here is a playground.