How to use the alternatives function from joi

Find comprehensive JavaScript joi.alternatives code examples handpicked from public code repositorys.

joi.alternatives is a method in the Joi library that allows for multiple valid schemas to be defined for a given data validation rule.

101
102
103
104
105
106
107
108
109
110

// Dependencies supported
dependencies: (
joi.object().optional()
  .pattern(RE_EMPTY, joi.forbidden())
  .pattern(RE_NOT_EMPTY, joi.alternatives().try(
    joi.string().required(),
    joi.object().required()
      .keys({
        name: joi.string().default('*'),
fork icon816
star icon0
watch icon338

+ 7 other calls in file

66
67
68
69
70
71
72
73
74
75
    sdAdmins: joi.array().default([]),
    bell: joi.object().required(),
    scm: joi.object().required(),
    sessionTimeout: joi.number().integer().positive().default(120),
    oauthRedirectUri: joi.string().optional(),
    sameSite: joi.alternatives().try(JOI_BOOLEAN, joi.string()).required(),
    path: joi.string().required()
});

/**
fork icon163
star icon972
watch icon65

+ 3 other calls in file

How does joi.alternatives work?

joi.alternatives is used to define alternative schemas that can be used for validating data, where each alternative schema may have different validation rules. It can be used in cases where the data being validated may take on different structures or formats, and multiple schemas need to be checked to determine whether the data is valid. joi.alternatives takes an array of schema objects, and the validation process will succeed if at least one of the schemas is valid. The order of the schemas in the array is important, as the first valid schema will be used to validate the data. If none of the schemas are valid, then the validation process fails. Additionally, joi.alternatives can be used with conditional validation, where the schema used for validation is determined by some criteria in the data being validated. This can be achieved by using a when clause in the schema definition, which allows for conditional rules to be applied based on the values of other properties in the data. Overall, joi.alternatives provides a flexible way to validate data that may have multiple valid structures, or where the validation rules may vary based on the content of the data.

16
17
18
19
20
21
22
23
24
25
});

internals.configSchema = Joi.object().keys({
  hashKey   : Joi.string().required(),
  rangeKey  : Joi.string(),
  tableName : Joi.alternatives().try(Joi.string(), Joi.func()),
  indexes   : Joi.array().items(internals.secondaryIndexSchema),
  schema    : Joi.object(),
  timestamps : Joi.boolean().default(false),
  createdAt  : Joi.alternatives().try(Joi.string(), Joi.boolean()),
fork icon87
star icon292
watch icon8

+ 11 other calls in file

1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
cancelReason: Joi.string().optional(),
task: Joi.object()
  .keys({
    isTask: Joi.boolean().default(false),
    isAssigned: Joi.boolean().default(false),
    memberId: Joi.alternatives().try(Joi.string().allow(null), Joi.number().allow(null)),
  })
  .optional(),
billing: Joi.object()
  .keys({
fork icon44
star icon17
watch icon25

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const Joi = require("joi");

// Define two alternative schemas for the JSON object
const schema1 = Joi.object({
  type: Joi.string().valid("type1"),
  value1: Joi.string().required(),
});

const schema2 = Joi.object({
  type: Joi.string().valid("type2"),
  value2: Joi.number().required(),
});

// Combine the two schemas into a single schema using joi.alternatives
const schema = Joi.alternatives().try(schema1, schema2);

// Validate some sample data against the schema
const data1 = {
  type: "type1",
  value1: "some value",
};

const data2 = {
  type: "type2",
  value2: 123,
};

const invalidData = {
  type: "invalid",
  value: "some value",
};

const result1 = schema.validate(data1);
console.log(result1); // { value: { type: 'type1', value1: 'some value' }, error: null }

const result2 = schema.validate(data2);
console.log(result2); // { value: { type: 'type2', value2: 123 }, error: null }

const result3 = schema.validate(invalidData);
console.log(result3.error); // ValidationError: "type" must be [type1, type2]

In this example, schema1 and schema2 define two different schemas for the JSON object, which have different validation rules. These two schemas are then combined into a single schema using joi.alternatives. The try method is used to specify that either schema1 or schema2 must be valid. The resulting schema object can then be used to validate JSON objects that conform to either schema1 or schema2. If the input data conforms to either of the schemas, the validation process will succeed and return an object with a value property containing the validated data. If the input data does not conform to either schema, the validation process will fail and return an error object.

79
80
81
82
83
84
85
86
87
88
    site: joi.string(),
}).required(),
topic: joi.string().required(),
groupId: joi.string().required(),
queueProcessor: joi.func(),
fromOffset: joi.alternatives().try('latest', 'earliest', 'none'),
concurrency: joi.number().greater(0).default(CONCURRENCY_DEFAULT),
fetchMaxBytes: joi.number(),
canary: joi.boolean().default(false),
bootstrap: joi.boolean().default(false),
fork icon18
star icon51
watch icon60

+ 3 other calls in file

214
215
216
217
218
219
220
221
222
223
reducedMobilityAccess: Joi.alternatives().conditional("moreInformation", {
  is: "true",
  then: needRequired(Joi.string().trim().valid("true", "false"), isRequired),
  otherwise: Joi.isError(new Error()),
}),
handicapInSameDepartment: Joi.alternatives().conditional("moreInformation", {
  is: "true",
  then: needRequired(Joi.string().trim().valid("true", "false"), isRequired),
  otherwise: Joi.isError(new Error()),
}),
fork icon4
star icon8
watch icon4

+ 101 other calls in file

809
810
811
812
813
814
815
816
817
818
if (!canViewYoungFile(req.user, young)) return res.status(403).send({ ok: false, code: ERRORS.OPERATION_UNAUTHORIZED });

// Validate files with Joi
const { error: filesError, value: files } = Joi.array()
  .items(
    Joi.alternatives().try(
      Joi.object({
        name: Joi.string().required(),
        data: Joi.binary().required(),
        tempFilePath: Joi.string().allow("").optional(),
fork icon4
star icon8
watch icon4

+ 9 other calls in file

41
42
43
44
45
46
47
48
49
50
        lastName: Joi.string().min(1).max(255).description('User last name'),
        phoneNumber: Joi.string().description('User phone number'),
        'role_id': Joi.number().integer().default(3)
    }).options({ stripUnknown: true });

    return Joi.alternatives().try(user, Joi.array().items(user.required()));
};

/**
 * @api {get} /users/:username Get one user
fork icon1
star icon8
watch icon5

56
57
58
59
60
61
62
63
64
65
hostname: joi.string(),
port: joi.number().integer(),
protocol: joi.string(),
strict: joi.boolean().default(false),
relsPath: joi.string().default('/rels'),
relsAuth: joi.alternatives().try(joi.boolean().allow(false),joi.object()).default(false),
relsTemplate: joi.boolean().default(true),
autoApi: joi.boolean().default(true),
apiPath: joi.string().allow('').default('/api'),
apiAuth: joi.alternatives().try(joi.boolean().allow(false),joi.object()).default(false),
fork icon23
star icon0
watch icon1

+ 7 other calls in file

303
304
305
306
307
308
309
310
311
312
313
314


internals.mongooseValidateWrapper = async (originalJoiSchema, value) => {
  let joiSchema = Hoek.clone(originalJoiSchema);


  if (joiSchema._isObjectId) {
    joiSchema = Joi.alternatives(
      joiSchema,
      Joi.object().instance(internals.mongoose.Types.ObjectId)
    );
  }
fork icon22
star icon180
watch icon0

+ 2 other calls in file

74
75
76
77
78
79
80
81
82
}

if (Joi.isSchema(routeQueryValidation)) {
    if (!validateDescription) {
        let schemaDescription = routeQueryValidation.describe()
        // if schema has Joi.alternatives(), use first schema-alternative
        if (schemaDescription.matches) {
            schemaDescription = schemaDescription.matches[0].schema
        }
fork icon4
star icon6
watch icon34

28
29
30
31
32
33
34
35
36
37
38
const Hoek = require('@hapi/hoek');
const Resolver = require('./resolver');
const Store = require('./store');


const schema = Joi.object({
    config: Joi.alternatives(Joi.string(), Joi.object()).required(),
    basedir: Joi.string(),
    criteria: Joi.object().default({}),
    protocols: Joi.object().default({}),
    defaults: Joi.alternatives(Joi.string(), Joi.object()).default({}),
fork icon7
star icon2
watch icon4

+ 17 other calls in file

74
75
76
77
78
79
80
81
82
83
  } catch (err) {
    return Boom.badImplementation(err.message, err)
  }
},
validate: {
  query: Joi.alternatives().required().try(Joi.object().keys({
    easting: Joi.number().max(700000).positive().required(),
    northing: Joi.number().max(1300000).positive().required(),
    location: Joi.string().required(),
    fullName: Joi.string(),
fork icon3
star icon2
watch icon11

+ 11 other calls in file

155
156
157
158
159
160
161
162
163
164
describe('returns an array of valid objects', function() {
  var schema = Joi.object().keys({
                amdPath: Joi.string().required(),
                name: Joi.string().required(),
                path: Joi.string().required(),
                doc: Joi.alternatives().try(Joi.string(), null),

                caniuse: Joi.alternatives().try(Joi.string(), null),

                async: Joi.boolean(),
fork icon1
star icon0
watch icon2

+ 7 other calls in file

39
40
41
42
43
44
45
46
47
48
49
  txnId: Joi.string().uuid({ version: 'uuidv4' }).required()
})


const initLoginAadhaar = Joi.object({
  authMethod: Joi.string().valid('AADHAAR_OTP').required(),
  healthId: Joi.alternatives()
    .try(
      Joi.string().length(14),
      Joi.string()
        .regex(/([0-9][0-9])(-[0-9][0-9][0-9][0-9])*/)
fork icon1
star icon0
watch icon3

+ 23 other calls in file

47
48
49
50
51
52
53
54
55
56
    type: joi.string().valid("upload", "delete", "submit").required(),
    content: joi.string().max(500).allow(""),
    deletepath: joi
      .alternatives()
      .try(joi.string(), joi.array().min(1).max(9)),
    filepath: joi.alternatives().try(joi.string(), joi.array().min(1).max(9)),
  }),
},
{
  path: "/api/blog/updata",
fork icon0
star icon0
watch icon1

+ 29 other calls in file

33
34
35
36
37
38
39
40
41
42
43
    return helper.message({ custom: `(${helper.state.path.join('.')} = ${value}) does not match regexp: /^(-?\\d+) (minute|hour|day|week|month|quarter|year)$/` });
  }
});


const timeInterval =
  Joi.alternatives([
    regexTimeInterval,
    Joi.any().valid('unbounded')
  ]);

fork icon0
star icon0
watch icon149

+ 49 other calls in file

195
196
197
198
199
200
201
202
203
204
const schema = Joi.alternatives().try(
    Joi.string().valid('key'),
    Joi.number().valid(5),
    Joi.object({
        a: Joi.boolean().valid(true),
        b: Joi.alternatives().try(
            Joi.string().pattern(/^a/),
            Joi.string().valid('boom')
        )
    })
fork icon0
star icon0
watch icon176

+ 7 other calls in file

39
40
41
42
43
44
45
46
47
48
const definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];
const schema = Joi.compile(definition);

// Same as:

const schema = Joi.alternatives().try([
    Joi.string().valid('key'),
    Joi.number().valid(5),
    Joi.object().keys({
        a: Joi.boolean().valid(true),
fork icon0
star icon0
watch icon0

+ 3 other calls in file

232
233
234
235
236
237
238
239
240
241
var definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];
var schema = Joi.compile(definition);

// Same as:

var schema = Joi.alternatives().try([
    Joi.string().valid('key'),
    Joi.number().valid(5),
    Joi.object().keys({
        a: Joi.boolean().valid(true),
fork icon0
star icon0
watch icon2

+ 3 other calls in file