繁体   English   中英

如何在joi模式中运行自定义验证功能

[英]How to run custom validation function in the joi schema

我要基于架构中未包含的内容将字段设置为强制或可选。 例如,某些东西存储在全局范围内。 这是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 ,否则将其some_global_scope_var可选?

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

使用$字符访问全局范围

通常,您将访问没有前缀的相对属性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));

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM