最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate whether a username is unique using joi? - Stack Overflow

programmeradmin1浏览0评论

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. I can't find it now and I want to know how can we do that with 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. I can't find it now and I want to know how can we do that with Joi.

Share Improve this question asked Nov 1, 2017 at 12:05 sidoshisidoshi 2,1603 gold badges18 silver badges30 bronze badges 3
  • 5 I'd be interested to see what you've tried so far. I'd argue this isn't really Joi's intended use as a schema validator though. What you're describing is presumably a second level of validation once Joi has confirmed the request is valid that you'll need to implement yourself. – Ankh Commented Nov 2, 2017 at 8:01
  • I had no luck finding how to do that. I guess you are right. I should use Joi only for schema validation and do async checks on some next level. It still beats me that I cant find that article. – sidoshi Commented Nov 2, 2017 at 10:58
  • 2 This is what pre handlers are useful for. – Shawn C. Commented Nov 2, 2017 at 20:41
Add a ment  | 

1 Answer 1

Reset to default 6

As @Ankh already mentioned in the ments, I also think that checking the database isn't joi's area of responsibility.

However with joi@v16 and any().external() you can now do an external async validation. This can be used to do a database lookup. (Details in release document 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');
发布评论

评论列表(0)

  1. 暂无评论