How to validate uniqueness in DB via Joi.validate?

Viewed 2802

Is this possible to insert a function to a Joi validation schema which will check in the DB if the value is unique?

(The check will be done by a function that I make, inside Joi function method).

Maybe something like this:

phone: Joi.customCheck(function(v) {
  let bool;
  // check in DB if v is already exists, then assign the value to bool...
  return bool;
}).required()

I have searched in Google and in the Joi api reference but found nothing.

1 Answers

You can use the new function any().external() (since version 16.0.0). This can be used to do a database lookup.

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');
Related