Search code examples
javascriptjoi

How to get value of another property with Joi?


How can I define property of resulting value if I have optional schema property like:

passport: customJoi.string().optional().strip(true),
passportSeries: ? // return passport ? passport.slice(0,4) : undefined,

I tried to use when and custom but it seems that they work only if passportSeries in original object are defined and it looks like I don't have access to passport property anyway.


Solution

  • You can make use of the ref method in joi, which allows you to refers to another field in the object:

    Joi.object({
      passport: Joi.string().optional().strip(true),
      passportSeries: Joi.ref('passport', {
        adjust: (val) => val.slice(0, 4),
      }),
    });
    

    By default, Joi.ref('field') refers to the exact value of the field, which is usually helpful for cases like password and confirm_password. However, you can make use of the second argument options.adjust that allows you to adjust the value before matching.


    However, I think the question is a bit ambiguous here. If your purpose is to create another property based on an existing property, you can make use of forbidden method and default method instead:

    Joi.object({
      passport: Joi.string().optional().strip(true),
      passportSeries: Joi.forbidden().default(
        Joi.ref('passport', { adjust: (val) => val.slice(0, 4) })
      ),
    });
    

    Basically, you mark the property passportSeries as forbidden(), which means this key cannot exists in your original object. However, with the use of default() you can set a value based on another value with the help of ref() method.