Skip to content

How to conditionally require a field? #297

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

You must be logged in to vote

I recommend to write the following. union has no pipe argument yet, that's why I added the validation to object and forwarded the error to name. I plan to improve that.

Whenever nameUnknown.value is true or name is a string, the input is valid. Otherwise the error message is displayed.

import { custom, forward, minLength, null_, nullable, object, string, union } from 'valibot';

const nameUnknown = ref(false);

// Currently
const schema = object(
  {
    name: nullable(string([minLength(1)])),
  },
  [
    forward(
      custom(
        (input) => nameUnknown.value || typeof input.name === 'string',
        'Name is required.'
      ),
      ['name']
    ),
  ]
);

// Planned improvement

Replies: 1 comment 8 replies

Comment options

You must be logged in to vote
8 replies
@ewautr
Comment options

@fabian-hiller
Comment options

Answer selected by ewautr
@ewautr
Comment options

@fabian-hiller
Comment options

@fabian-hiller
Comment options

@fabian-hiller
Comment options

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