![](/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.