【问题标题】:Add error in existing errors while validating object through hapi/joi通过 hapi/joi 验证对象时在现有错误中添加错误
【发布时间】:2020-04-10 21:14:48
【问题描述】:
const schema = Joi.object().keys({
              Id: Joi.number().required(),
              CustomerName: Joi.string()
                .trim()
                .required()
                .when('$isInValidCustomer', {
                  is: true,
                  then: //Add some error in existing error block,
                }),
               BankName: Joi.string().trim(),
            });

const custDetail = {
Id: 2,
CustomerName: 'xyz'
BankName: ''
};

const schemaOptions = {
              abortEarly: false,
              context: {
                isInValidCustomer: true,
              },
            };

const valError = schema.validate(custDetail, schemaOptions);

所以,现在当我验证“custDetail”对象时,我想要以下 2 个错误: - CustomerName 错误,因为 'isInValidCustomer' 为真 - 需要银行名称

我无法在现有错误对象中附加 CustomerName 的错误。如果我使用“.error()”,那么只会得到与“CustomerName”相对应的单个错误,否则只会得到 BankName 的错误。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript node.js validation hapijs joi


    【解决方案1】:

    这可以使用自定义函数来实现。

    const schema = Joi.object().keys({
                  Id: Joi.number().required(),
                  CustomerName: Joi.string()
                    .trim()
                    .required()
                    .when('$isInValidCustomer', {
                      is: true,
                      then: Joi.any().custom(() => {
                        throw new Error('Invalid Customer');
                        }),
                    }),
                   BankName: Joi.string().trim(),
                });
    

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2015-04-29
      • 1970-01-01
      • 2019-05-05
      • 2020-06-14
      • 2020-01-17
      • 2020-09-13
      • 2018-06-25
      • 2018-09-24
      相关资源
      最近更新 更多