fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
6.32k stars 204 forks source link

Using other keys for validation? #931

Open hongkongkiwi opened 4 days ago

hongkongkiwi commented 4 days ago

Using valibot, how can I validate against other fields in the schema?

For example, I have a schema like this:

  v.object({  
    saveToS3: v.optional(v.boolean(), false),
    s3Config: v.optional(v.object({
      bucket: v.string(),
      region: v.optional(v.string(), 'us-east-1'),
      key: v.optional(v.string()),
    })),
  }),

I would like to validate that if saveToS3 is true then s3Config must be present and contain the bucket key.

I know that we can use custom validation methods, but I couldn't quite see how I would access other keys within that method.

ivanbarlog commented 4 days ago

You should use v.variant() in order to achieve this.

Here is the link for the playground with an example.