Require at least one non-empty child in a joi object that allows null

I am defining a Joi schema for an entity with some fields for social profiles. The goal is to make sure that all fields are present and that at least one of them is a non-empty string, but that the rest are null

.

Here's what I have so far:

const socialUrl = joi.string().min(1).alphanum().allow(null);
const schema = joi.object({
    facebook : socialUrl.required(),
    twitter  : socialUrl.required(),
    youtube  : socialUrl.required()
}).required()

      

This works great, except that the following object is considered valid:

{
    facebook : null,
    twitter  : null,
    youtube  : null
}

      

Using min () and or () on the object doesn't help, because the fields exist, they're just the wrong type.

It would be quite trivial to do an extra loop after itself and check the specific case of all fields null

, but this is not ideal.

This is used to validate useful information , where it would be good to know that the client understands the complete schema, hence the desire for all fields. Maybe it's not worth it. I make sense that I could use some verbose when () code to get the job done, but it looks like at this point I could as well just make my own loop. Hope it goes wrong!

+3


source to share


1 answer


here is the finished answer: Using Joi, you need one of the two fields to be non-empty

joi has a .alternatives()

method that has a method .try()

where you can just go through all the parameters In each case you only have to store one fieldrequired



const socialUrl = joi.string().min(1).alphanum().allow(null);

const schema = joi.alternatives().try(
  joi.object({
    facebook: socialUrl.required(),
    twitter: socialUrl,
    youtube: socialUrl,
  }),
  joi.object({
    facebook: socialUrl,
    twitter: socialUrl.required(),
    youtube: socialUrl,
  }),
  joi.object({
    facebook: socialUrl,
    twitter: socialUrl,
    youtube: socialUrl.required(),
  }),
);

      

This way you don't need to use .min()

or.or()

0


source







All Articles