问题描述
我使用 Joi
根据架构验证我的输入。
如何访问 foo
函数内的 custom
值?
import * as Joi from "joi";
console.clear();
const schema = Joi.object({
bar: Joi.string().custom((x) => {
// how to access foo value?
console.log({ x });
}),foo: Joi.string()
});
schema
.validateAsync({ foo: "myfoo",bar: "mybar" })
.then((x) => {
console.log({ x });
})
.catch((err) => {
console.log({ err });
});
解决方法
如果您想访问其他一些键,您需要向对象添加自定义验证:
const schema = Joi.object({
bar: Joi.string(),foo: Joi.string()
}).custom((obj,helpers) => {
// you have access to the full object above.
const { foo,bar } = obj;
if (foo === "myfoo") {
}
});