Search code examples
javascripttypescriptjoi

Joi validate one of two schemas


I have a simple object with few fields that I would like to validate. I wish to allow or a specific validation schema or that all of the properties have empty values

I created the following two schemas:

 const nonEmptyUserInfoValidationSchema = Joi.object({
    url: Joi.string().uri().required(),
    username: Joi.string().required().min(usernameMinLength),
    password: Joi.string().required().min(passwordMinLength),
});

const emptyUserInfoValidationSchema = Joi.object({
    url: Joi.string().empty().required(),
    username: Joi.string().empty().required(),
    password: Joi.string().empty().required(),
});

I wish to create schema that validates if emptyUserInfoValidationSchema or nonEmptyUserInfoValidationSchema is applied but I can't figure out how to do it, any suggestions?

allowed:

{url:"http://some.url", username:"some username", password:"some password"}
{url:"", username:"", password:""}

not allowed:

{url:"http://some.url",  username:"", password:""}

Solution

  • Well I finally found what I was looking for joi.alternatives:

    export const ansibleInfoValidationSchema = Joi.alternatives(emptyUserInfoValidationSchema , nonEmptyUserInfoValidationSchema );
    

    seems to do the trick