简体   繁体   中英

How to do @hapi/joi validation for the following?

In the following schema i need like , if type is withdraw => [name,accountNumber,ifscCode,branchName,comments,upiId,amount,bonus,userId] to pass but if type is deposit i need => [txnReferenceId,amount,bonus,userId] to pass.

    const withdrawDepositValidatorSchema = Joi.object({
        type: Joi.string(),
        name: Joi.string(),
        accountNumber: Joi.number(),
        ifscCode: Joi.string().alphanum(),
        branchName: Joi.string(),
        comments: Joi.string(),
        upiId: Joi.string(),
        txnReferenceId: Joi.number(),
        amount: Joi.number(),
        bonus: Joi.number(),
        userId: Joi.string()
    })

You can use when condition. I am giving one example here but can be done for other fields as well.

const withdrawDepositValidatorSchema = Joi.object({
  type: Joi.string(),
  name: Joi.when(Joi.ref("type"), {
    "is": Joi.string().valid("Withdraw"),
    "then": Joi.string(),
    "otherwise": Joi.forbidden()
  }),

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