繁体   English   中英

如何从 Joi 中已定义的架构 object 中访问/提取架构?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM