如何从Joi中已经定义的模式对象中访问/提取模式



我已经定义了这个模式。

schema = Joi.object({
username: Joi.string().min(5).max(32).required().label('Username'),
password: Joi.string().min(8).max(50).required().label('Password')
});

我知道我需要同时传递有效的用户名和密码值才能不出错。

但是,我每次只需要根据这个模式验证一个字段。这意味着,如果我传递了一个有效的用户名,我希望这个模式不会返回错误。

以下是我所做的:

validateOneField(name, value){
// create an object  dynamically
const obj = { [name] : value };
// here I need to get the schema for either username or password depending upon name argument.
// how can I create a schema dynamically here?
// example:
const schema = Joi.object({ this.schema[name] }); // I know this won't work!
// and validate only single value
const { error } = schema.validate(obj);
console.log(error);
}

有没有其他访问模式的方法,比如this.schema[用户名]或this.schema[密码]?

提前谢谢!

您可以使用extract方法来获得您想要的规则

validateOneField(name, value){
const rule = this.schema.extract(name);
const { error } = rule.validate(value);
console.log(error);
}

在Gabriele Petrioli的帮助下,我完成了这项工作。

代码:

validateProperty = ({name, value}) => {
const obj = { [name] : value };
const rule = this.schema.extract(name);
const schema = Joi.object({ [name] : rule});
const { error } = schema.validate(obj);
return (!error) ? null : error.details[0].message;
};

谢谢大家!

最新更新