Ask Your Question
0

How can a Joi validation be created to ensure that an array of numbers is between 1-2 length and that the first element is smaller than the second?

asked 2023-06-28 11:26:42 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-28 11:27:02 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-28 11:26:42 +0000

Seen: 10 times

Last updated: Jun 28 '23