How can I specify a custom error message for a Joi xor()?

Viewed 494

I've got a schema where one of two optional forms can be added at runtime and one of them must be added to pass validation. I've got that bit working with the use of an xor() but I want to set a custom error message like "You must add a formA or formB to continue" instead of the default "value" must contain at least one of [formA, formB].

I've tried calling .xor().message() but I get the error

Error: Cannot apply rules to empty ruleset or the last rule added does not support rule properties

How can I specify a custom error message for a Joi xor() ?

2 Answers

This works for Joi version 17.2.1

const Joi = require('joi');

const schema = Joi.object().keys({
   formA: Joi.string(),
   formB: Joi.string(),
})
.xor('formA', 'formB')
.messages({
  'object.xor': 'You must add a formA or formB to continue'
})
.required()

const data = {
  formA: 'formA',
  formB: 'formB'
};

const report = schema.validate(data)
console.log(report.error.message)

Output

You must add a formA or formB to continue

When both keys are missing you should use object.missing.

object.xor error appears when both keys are present.

.xor('formA', 'formB')
.messages({
  'object.missing': 'You must add a formA or formB to continue',
  'object.xor': 'You must provide either formA or formB'
})
Related