【问题标题】:joi.label , what does this method of joi schema validation dojoi.label ,这种 joi 模式验证方法有什么作用
【发布时间】:2023-03-21 05:45:02
【问题描述】:

我刚刚遇到了我必须处理的这行代码:

Joi.array().label('Emails').items(Joi.string()).required()

我特别不明白.label('Emails')在做什么,所以,我点击了文档:

覆盖错误消息中的键名。

name - the name of the key.

常量模式 = { first_name: Joi.string().label('First Name') };

这对我来说尤其没有任何意义。因为,是First NameEmails可以传递的特定参数吗?什么是压倒一切的?我们还可以传递哪些其他参数等。这个方法具体做了什么?

【问题讨论】:

    标签: joi


    【解决方案1】:

    如果你有这个架构:

    const schema = Joi.object({
      first_name: Joi.string().label('First Name')
    });
    

    并且您验证了一个无效对象(将first_name 作为number 类型传递):

    const { error, value } = schema.validate({ first_name: 123 })
    

    error.details 对象的外观如下:

    [
      {
        message: 'first_name must be a string',
        path: [ 'first_name' ],
        type: 'string.base',
        context: {
          label: 'First Name',
          valids: 123,
          key: 'first_name'
        }
      }
    ]
    

    但是,如果您使用.label('First Name'),这就是您从错误对象中得到的:

    [
      {
        message: 'First Name must be a string', <-- OVERRIDES
        path: [ 'first_name' ],
        type: 'string.base',
        context: {
          label: 'First Name', <-- OVERRIDES
          valids: 123,
          key: 'first_name'
        }
      }
    ]
    

    因此,.label 将覆盖 messagecontext.label

    根据documentation,您不能传递任何其他参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 2015-02-11
      • 2010-12-20
      相关资源
      最近更新 更多