Gibran Shah
Gibran Shah

Reputation: 1109

How do I interpret this JOI validation code (version 17.8.3)?

I've got the follow JOI code for validating data:

const abcSchema = Joi.object().keys({
  value: Joi.when('...objectType', {
    is: Joi.string().valid('Unknown').insensitive(),
    then: Joi.optional().allow(null),
    otherwise: Joi.number().positive().required(),
  });

export const schema = Joi.object().keys({ abc: abcSchema });

Please let me know if I'm interpreting this correctly: it's saying that on an object where the objectType field has a value of 'Unknown' (case insensitive), the abc field is optional and can be null. Otherwise (if it's a different value than null or the objectType field is not 'Unknown'), then the abc field is required and must be a positive number.

Is this correct?

What if I'm trying to validate an object that looks like this:

{
    ...
    "objectType": {
        "type": "UNKNOWN",
        ...
    }
    ...
    "abc": {
        "value": null,
        ...
    }
    ...
}

...and it gives back this validation message: "abc : value" must be a number"

So abc.value is null, and objectType.type is 'UNKNOWN' yet it seems to be falling back on the otherwise validation rule. Why is that?

I'm using Joi 17.8.3.

Upvotes: 0

Views: 33

Answers (0)

Related Questions