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
.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With