Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is an example Joi validation schema that ensures an array of numbers is between 1-2 length and that the first element is smaller than the second:

const Joi = require('joi');

const schema = Joi.array().ordered(
  Joi.number(),
  Joi.number().greater(Joi.ref('$first'))
).max(2).min(1);

const input1 = [1, 2];    // Valid
const input2 = [3, 4, 5]; // Invalid

const result1 = schema.validate(input1); // { value: [1, 2], error: null }
const result2 = schema.validate(input2); // { value: null, error: <Joi.ValidationError> }

Explanation: - We use the Joi.array() method to create a validation schema for an array. - We use the ordered() method to ensure that the first element is smaller than the second. We pass in two Joi.number() validators to enforce that both array elements are numbers, and the second validator passes the $first value (the first element in the array) as the minimum value via the Joi.ref() method. - We use the max() and min() methods to enforce that the length of the array is between 1-2 inclusive. - Finally, we call the .validate() method on the schema with the array input to obtain the validation result. The result contains a value field that holds the validated input or null if validation failed, and an error field that holds a Joi.ValidationError object if validation failed or null if validation succeeded.