[英]how to access/extract a schema from an already defined schema object in Joi?
I have this schema defined.我已经定义了这个模式。
schema = Joi.object({
username: Joi.string().min(5).max(32).required().label('Username'),
password: Joi.string().min(8).max(50).required().label('Password')
});
I know that I need to pass both valid username and password values to get no errors.我知道我需要同时传递有效的用户名和密码值才能避免错误。
But, I need to validate only one field at a time against this schema.但是,我一次只需要针对这个模式验证一个字段。 this means, if I pass a valid username, I want this schema to return no errors.
这意味着,如果我传递了一个有效的用户名,我希望这个模式不返回任何错误。
Here is what I have done:这是我所做的:
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);
}
Is there any other way to access the schema like: this.schema[username] or this.schema[password]?有没有其他方法可以访问架构,例如:this.schema[username] 或 this.schema[password]?
Thank you in advance!先感谢您!
With the help of Gabriele Petrioli's answer I was able to get this done.在 Gabriele Petrioli 的回答的帮助下,我能够完成这项工作。
Code:代码:
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;
};
Thank You Guys!感谢你们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.