【问题标题】:Validate two properties are equal验证两个属性是否相等
【发布时间】:2020-01-02 14:30:27
【问题描述】:

是否可以使用Joi 验证两个string 类型的对象属性是否相等?

我找到了Joi.ref(),但我想知道是否还有其他方法。特别是Joi.ref() 似乎不支持any.error()

【问题讨论】:

  • 我记得你,你创建了 npm 包docker-compose,谢谢!你能详细描述一下你想用any.error()做什么吗?密码是否应该与另一个密码匹配?您想要哪些错误消息?
  • 密码匹配正是这里的预期用例。如何使用Joi 并不重要。我只想尽可能使用Joi
  • 我找到了一个适用于Joi.ref()的解决方案

标签: javascript joi


【解决方案1】:

是的,可以检查一个对象的两个属性是否相同。使用Joi.ref() 是首选方式。

如果您想使用自定义错误消息Joi.any.messages() 选项效果最好。 Joi.any.messages() 允许您覆盖属性产生的不同错误消息。

您也可以使用Joi.any.error() 选项,但这不是那么优雅,您需要在不同的错误代码之间使用switch(如string.baseany.requiredany.only...)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多