1

How can I create a validation rule using Joi that enforces the following condition: if valueA is empty, then valueB should have a value, and vice versa?

I'm currently using Joi to validate an array of objects that have valueA and valueB properties. Here's an example of the schema I'm using:

const schema = Joi.object({
  valueA: Joi.string().pattern(/^\d+(,\d{1,2})?(\.\d{1,2})?$/)
  valueB: Joi.string().pattern(/^\d+(,\d{1,2})?(\.\d{1,2})?$/)
});

I want to modify this schema to enforce the validation rule that either valueA or valueB has a value, and the other is empty. How can I do this using Joi?

Nicke7117
  • 187
  • 1
  • 10
  • Possible duplicate of [Joi either or validation](https://stackoverflow.com/questions/35489652/joi-schema-should-contain-one-field-or-another) – Vaulstein Aug 08 '23 at 14:01

1 Answers1

0

You might be able to achieve this using alternatives().try()

Example:

const schema = Joi.alternatives().try(
  Joi.object().keys({
    valueA: Joi.string().pattern(/^\d+(,\d{1,2})?(\.\d{1,2})?$/),
    }),
  Joi.object().keys({
    valueB: Joi.string().pattern(/^\d+(,\d{1,2})?(\.\d{1,2})?$/)
    })
);

alternatives().try() adds an alternative schema type for attempting to match against the validated value. You are passing two options and it will choose one of them.

Vaulstein
  • 20,055
  • 8
  • 52
  • 73
  • No, because when using `or()`, both can have values which I do not want to happen. – Nicke7117 Aug 08 '23 at 14:56
  • @Nicke7117 Updated answer. Check https://stackoverflow.com/questions/28864812/using-joi-require-one-of-two-fields-to-be-non-empty – Vaulstein Aug 08 '23 at 15:01