Skip to content

Cross-field validation #19

@iainsproat

Description

@iainsproat

Given the following schema, I wish for the validation of FLAG_B_DEPENDS_ON_FLAG_A to depend on the value of FLAG_A:

parseEnv(process.env,
  {
    FLAG_A: {
      schema: z.boolean(),
      defaults: { _: false }
    },
    FLAG_B_DEPENDS_ON_FLAG_A: {
      schema: z.boolean(),
      defaults: { _: false }
    }
  })

In Zod cross-field validation can be achieved via .refine on the object, e.g.:

z.object(
  {
    FLAG_A: {
      schema: z.boolean(),
      defaults: { _: false }
    },
    FLAG_B_DEPENDS_ON_FLAG_A: {
      schema: z.boolean(),
      defaults: { _: false }
    }
  }).refine({ FLAG_A, FLAG_B_DEPENDS_ON_FLAG_A }=> {
      if (FLAG_B_DEPENDS_ON_FLAG_A && !FLAG_A) {
        return false
      }

      return true;
    },
    () => ({
      path: ['FLAG_A'],
      message: '`FLAG_A` field is required to be true if `FLAG_B_DEPENDS_ON_FLAG_A` is true',
    })
  );

How might this be achieved with znv?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions