![](/img/trans.png)
[英]How to force joi to invoke custom function when the object schema is invalid?
[英]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.