简体   繁体   中英

Joi validation library for node: A field is required when another is not present

My schema has some 3 fields that have several conditions depending who is present:

  1. successUrl cannot be present without ** failUrl** (the same goes the other way around)

  2. responseUrl cannot be present if succesUrl and/or failUrl is present

  3. In the schema the pair successUrl and failUrl must be present if responseUrl is not (the same goes the other way around)

I managed to make the first 2 conditions to work, but the "when" method that is supposed to make responseUrl required when successUrl do not exist is ignored for some reason, so the schema validates when there is no successUrl, failUrl and responseUrl which violates my third condition.

const schema = Joi.object().keys({
    transaction: Joi.string().max(60),
    partner: Joi.string().regex(/^[0-9a-fA-F]{24}$/, 'Invalid partner ID').required(),
    amount: Joi.number().min(1).required(),
    responseUrl: Joi.string().uri().when('successUrl', { is: !Joi.exist(), then: Joi.string().uri().required() }),
    successUrl: Joi.string().uri(),
    failUrl: Joi.string().uri()
}).with('successUrl', 'failUrl').with('failUrl', 'successUrl').without('responseUrl', 'successUrl').without('responseUrl', 'failUrl');

I'm clearly using it wrong, link to reference .

I think I've managed to fix your schema using just .and() and .without() .

The following simplified version of your schema works:

const schema = Joi.object().keys({
    failUrl: Joi.string(),
    responseUrl: Joi.string(),
    successUrl: Joi.string()
})
    .or('failUrl', 'responseUrl', 'successUrl')
    .and('successUrl', 'failUrl')
    .without('responseUrl', [ 'successUrl', 'failUrl' ]);

The .or() forces the presence of at least one of the URLs. The .and() is to strictly require both or none of the keys inside. The .without() is to only allow a key when other keys aren't in the object.

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