简体   繁体   English

如何使用 joi 验证用户名是否唯一?

[英]How to validate whether a username is unique using joi?

I read an article somewhere in which the author used Joi to validate asynchronously, whether the username is unique or not by checking with the database.我在某处阅读了一篇文章,其中作者使用Joi通过检查数据库来异步验证用户名是否唯一。 I can't find it now and I want to know how can we do that with Joi .我现在找不到它,我想知道我们如何用Joi做到这一点。

As @Ankh already mentioned in the comments, I also think that checking the database isn't joi 's area of responsibility.正如@Ankh 在评论中已经提到的,我也认为检查数据库不是joi的职责范围。

However with joi@v16 and any().external() you can now do an external async validation.但是,使用joi@v16any().external()您现在可以进行外部异步验证。 This can be used to do a database lookup.这可用于进行数据库查找。 (Details in release document v16 ) (详细信息在发布文档 v16 中

const lookup = async (id) => {

    const user = await db.get('user', id);
    if (!user) {
        throw new Error('Invalid user id');
    }
};

const schema = Joi.string().external(lookup);
await schema.validateAsync('1234abcd');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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