10

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.

sidoshi
  • 2,040
  • 2
  • 15
  • 30
  • 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 Nov 02 '17 at 08: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 Nov 02 '17 at 10:58
  • 2
    This is what `pre` handlers are useful for. – Shawn C. Nov 02 '17 at 20:41

1 Answers1

6

As @Ankh already mentioned in the comments, 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');
a1300
  • 2,633
  • 2
  • 14
  • 18