[英]how to access/extract a schema from an already defined schema object in 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[username] 或 this.schema[password]?
先感謝您!
您可以使用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;
};
感謝你們!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.