【问题标题】:Validation using an external function in Joi (Node.js)在 Joi (Node.js) 中使用外部函数进行验证
【发布时间】:2019-12-03 20:02:30
【问题描述】:

我在我的 Node.js Rest API 中使用 Joi 进行验证。我有一个验证特定文档的函数,我想知道是否可以在 Joi 的验证中包含该函数。

例子:

function validateDocument (document) {
    return someCalculation;
}

const schema = Joi.object({
    document: Joi.string().required().valid(validateDocument) // I want something like that
});

const { error, value } = schema.validate(something);

【问题讨论】:

    标签: node.js validation joi


    【解决方案1】:

    是的。您可以使用Joi extension 调用外部函数进行验证。下面给出一个示例格式:

    const customSchema = Joi.extend(joi => ({
        base: joi.string(),
        name: 'customValidation',
        rules: [
            {
                name: 'validate',
                validate(params, value, state, options) {
                    // call custom function and return the result
                    // for instance:
                    return validateDocument(value);
                },
            },
        ],
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-11
      • 2020-08-04
      • 2023-02-15
      • 2022-06-26
      • 2020-03-01
      • 1970-01-01
      • 2018-08-30
      • 2022-01-25
      相关资源
      最近更新 更多