[英]How to validate sum of refs in Joi
如何驗證以下兩個參考的總數? 我更希望custom
在total
,但不確定在使用Joi.ref
時如何在 custom 中獲取refs
的值。
我可以執行以下操作並將custom
掛在整個驗證架構上,但更願意將其附加到total
。
我不想使用表達式()
我不想按照這個答案更改架構結構。
const widgetValidator = Joi.object({
a: Joi.number().integer().min(0).required(),
b: Joi.number().integer().min(1).required(),
total: Joi.number().integer().min(1).required(),
}).custom((value: {a: number; b: number; total: number;}, helpers) => {
if (value.total !== value.a + value.b) {
throw new Error('invalid balance calculation');
}
return value;
},
);
當您在屬性上安裝custom
時,獲取整個對象值會有點困難。 您必須從助手的狀態中獲取它:
Joi.object({
a: Joi.number().integer().min(0).required(),
b: Joi.number().integer().min(1).required(),
total: Joi.number().integer().min(1).required().custom((value, helpers) => {
const { a, b } = helpers.state.ancestors[0];
if (value !== a + b) {
throw new Error('invalid balance calculation');
}
return value;
},
)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.