Validate two properties are equal

2020-05-01 07:07发布

问题:

Is it possible to validate that two object properties of type string are equal using Joi?

I found Joi.ref() but I wonder if there's another way of doing it. Especially as Joi.ref() doesn't seem to support any.error()

回答1:

Yes, it is possible to check if two properties on a object are the same. And using Joi.ref() is the preferred way to do it.

If you want to use custom error messages the Joi.any.messages() option works the best. The Joi.any.messages() lets you overwrite the different error messages that a property is producing.

You could also use the Joi.any.error() option but that is not that elegant and you would need to switch between the different error codes (like string.base, any.required, any.only...)

Complete Solution using Joi.any.messages()

const Joi = require('@hapi/joi');

const schema = Joi.object().keys({
  first: Joi.string().required(),
  second: Joi.string().required().equal(Joi.ref('first'))
          .messages({
            'string.base': 'second is not a string', // typeof second !== 'string || second === null
            'any.required': 'second is required', // undefined
            'any.only': 'second must match first' // second !== first
          })
});

const value = {
  first: 'hello',
  second: 'hello',
};

const result = schema.validate(value);
console.log(JSON.stringify(result.error, null, 2));