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.
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
Asked: 2023-06-28 11:26:42 +0000
Seen: 10 times
Last updated: Jun 28 '23
How can one ensure that sub-classes have uniform method parameters in TypeScript?
How can the calculation of matrix determinant be performed using CUDA?
How can code repetition be prevented when using (box)plot functions?
When I attempt to generate a database, why does the azure-cosmos-emulator become unresponsive?
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?