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
.
- 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
1 Answer
Reset to default 6As @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');