How to apply .OR in joi validation

Viewed 4233

Well, i have the following Joi object, im trying to use Or method, as you see i have two objects contains phone i wanted to use Or method but i got failed

body: Joi.object().keys({
            member: Joi.object().required().keys({
                id: Joi.string().required(),
                phone: Joi.string().max(30),
                email: Joi.string().required().max(255)
            }),
            billingAddress: Joi.object().keys({
                line1: Joi.string().required(),
                line2: Joi.string().max(60),
                city: Joi.string().required().max(50),
                state: Jio.required(),
                postalCode: Joi.string().required(),
                phone: Joi.string().max(15)
            })
}).or('member.phone','billingAddress.phone')

what im trying to do is i need a phone either to be in member.phone or in billingAddress.phone at least one of them is exist the code above is not working What should i do ?

1 Answers

The functionality you're attempting to use has only recently gone into version 14.0.0 of Joi so the first step is to ensure you're requiring at least v14 of Joi.

Nested paths on object.or/nand/and/xor/with/without()

Nested paths on those functions are now supported. I consider this a breaking change as you may (but you really really shouldn't) have used dotted paths in those validations because you wanted to check dotted properties. If that's your case there is currently no migration path but we can discuss that in an issue.

For older versions it would require either a messy combination of .when() or .alternatives(), a custom validator or manually written logic with multiple schemas.

Related