【问题标题】:How to run custom validation function in the joi schema如何在 joi 模式中运行自定义验证功能
【发布时间】:2020-01-07 23:19:35
【问题描述】:

我想根据架构中没有的内容将字段设为必填或可选。例如,存储在全局范围内的东西。这是 Joi 架构:

first_name: Joi.string().min(2).max(10).regex(Regex.alphabeta, 'alphabeta').error(JoiCustomErrors)

如果some_global_scope_var 为1,如何使first_name 成为必填项,否则将其设为可选?

注意:some_global_scope_var 不是架构的一部分。

【问题讨论】:

  • 我的回答对你有用吗?您需要进一步的帮助吗?

标签: javascript validation schema joi


【解决方案1】:

使用$ 字符访问全局范围

通常您会访问不带前缀的相对属性last_name。对于全局访问,请在您的变量前加上 $

完整的解决方案

const Joi = require('@hapi/joi');

global.app = {
  someValue: 1,
};

const schema = Joi.object().keys({
  first_name: Joi.string()
                 .min(2)
                 .max(10)
                 .when('$app.someValue', {
                   is: Joi.equal(1),
                   then: Joi.required(),
                 })
});

const value = {
  first_name: 'a1300',
};

const result = schema.validate(value);
console.log(JSON.stringify(result.error, null, 2));

附:我省略了regex(Regex.alphabeta, 'alphabeta').error(JoiCustomErrors)

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 2019-03-21
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多