如何 access/extract 来自 Joi 中已定义模式对象的模式?

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')
    });

我知道我需要传递有效的用户名和密码值才能避免错误。

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

这是我所做的:

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;
    };

谢谢你们!