aladov3.13.0

Docs/Validation

Cross-Property Conditionals

Rules that look at sibling fields. The root context is passed automatically through .shape().

.when(key, is, then, otherwise?)

If root[key] === is, apply then validator; otherwise apply otherwise (optional). is can be a single value or an array of values.

TypeScript
const isContact = validate
  .object()
  .shape({
    type: validate.string().required().build(),
    contact: validate
      .string()
      .when(
        'type',
        'email',
        validate.string().email().build(), // when type === 'email'
        validate
          .string()
          .regex(/^\+\d+$/)
          .build(), // otherwise (phone)
      )
      .required()
      .build(),
  })
  .build();

await isContact({ type: 'email', contact: 'a@b.com' }); // true
await isContact({ type: 'phone', contact: '+123456' }); // true
await isContact({ type: 'email', contact: '+123456' }); // false

Array is — match multiple values:

TypeScript
validate
  .string()
  .when(
    'role',
    [
      'admin',
      'superadmin',
    ],
    allowedFn,
    restrictedFn,
  )
  .build();

.match(key, cases, fallback?)

Switch-case style — dispatch to different validators based on root[key].

TypeScript
const isLevel = validate
  .object()
  .shape({
    role: validate.string().required().build(),
    level: validate
      .number()
      .match(
        'role',
        {
          admin: validate.number().min(5).build(),
          viewer: validate.number().max(2).build(),
          editor: validate.number().min(1).max(4).build(),
        },
        validate.number().positive().build(),
      ) // fallback
      .required()
      .build(),
  })
  .build();

await isLevel({ role: 'admin', level: 7 }); // true
await isLevel({ role: 'viewer', level: 3 }); // false — max 2