Validate two properties are equal

最后都变了- 提交于 2019-12-11 05:58:43

问题


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));


来源:https://stackoverflow.com/questions/57708043/validate-two-properties-are-equal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!