Skip to content

Is conditional generation of pipes possible? #1029

Answered by fabian-hiller
ceigh asked this question in Q&A
Discussion options

You must be logged in to vote

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);
}

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@fabian-hiller
Comment options

@ceigh
Comment options

Answer selected by ceigh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants