Reputation: 157
I need to validate this object:
{a: 'valueA', b: 'valueB'}
To validate 'a' i need to check if his value (valueA) is present in my db. If the value is not present then the object is not valid, otherwhise is valid. How can I create a custom async/await with Joi validator to achieve this?
Upvotes: 5
Views: 4137
Reputation: 5552
You can add external validation using the any.external()
method, it receives a function as a parameter, so can be used to check the database for values.
The received functions' first parameter is the clone of the object you set to be validated. It runs after all other validations. If schema validation failed, no external validation rules are called.
const checkData = async (data) => {
const res = await db.find({ name: data.a }) // or any method you use
if (!res) {
throw new Error('Data not found in db!')
}
}
const schema = Joi.string().external(checkData)
await schema.validateAsync({ a: 'valueA', b: 'valueB' })
Upvotes: 2