Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 859
sidoshi Avatar asked Nov 01 '17 12:11

sidoshi


1 Answers

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');
like image 75
a1300 Avatar answered Sep 22 '22 21:09

a1300