微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

嵌套的 Joi 验证在使用时不起作用

如何解决嵌套的 Joi 验证在使用时不起作用

我一直在尝试嵌套 where 验证,但到目前为止没有运气。这是我想要实现的目标:

1- 如果 mainType 是 COMMERCIAL,则为 contactMethod 定义所需的架构。 2- 如果 isHousing 为 true,则为 contactMethod 定义所需的架构。 3- 如果 mainType 是 REAL_ESTATE,则不允许传递 contactMethod 对象

以下是我失败的尝试:

contactMethod: Joi.when('mainType',{
    is: 'COMMERCIAL',then: Joi.object()
        .keys({
            create: Joi.object({
                message: Joi.string().allow(''),}).required(),})
        .required()),}).when('isHousing',{
    is: true,})
        .required(),otherwise: Joi.disallow(),})

我也试过这个:

contactMethod: Joi.when('mainType',{
    switch: [
        {
            is: 'COMMERCIAL',then: Joi.object()
                .keys({
                    create: Joi.object({
                        message: Joi.string().allow(''),})
                .required(),},{
            is: 'REAL_ESTATE',then: Joi.when('isHousing',{
                is: true,then: Joi.object()
                    .keys({
                        create: Joi.object({
                            message: Joi.string().allow(''),})
                    .required(),}),],})   

那么我在这里做错了什么?

解决方法

好的,我是这样解决的:

contactMethod: Joi.when('mainType',{
        is: 'COMMERCIAL',then: Joi.object()
            .keys({
                create: Joi.object()
                    .keys({
                        message: Joi.string().allow(''),})
                    .required(),})
            .required(),otherwise: Joi.when('isHousing',{
            is: true,then: Joi.object()
                .keys({
                    create: Joi.object()
                        .keys({
                            message: Joi.string().allow(''),})
                        .required(),})
                .required(),otherwise: Joi.forbidden(),}),})

我的尝试没有包含上面@hoangdv 建议的键 ({}) + 我还需要将 disallow() 更改为禁止。

希望这对未来的人有所帮助。

,

就像你在第一层所做的那样 - 使用 .keys({}) 来定义对象属性。

contactMethod: Joi.when('mainType',{
  is: 'COMMERCIAL',then: Joi.object()
    .keys({
      create: Joi.object() // You missing usage of Joi.object()
        .keys({ // should define object attribute here
          message: Joi.string().allow(''),})
        .required(),})
    .required(),}).when('isHousing',{
  is: true,then: Joi.object()
    .keys({
      create: Joi.object() // the same :|
        .keys({
          message: Joi.string().allow(''),otherwise: Joi.disallow(),});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。