简体   繁体   中英

Joi async custom validation

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?

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' })

More information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM