如何从 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;
    };

谢谢你们!