Search code examples
javascriptverificationjoi

i have a problem with Joi validator for validation an array


let schema=Joi.array().length(2).items(Joi.number().integer().max(23).min(0).required(),Joi.number().integer().max(59).min(0).required())
        if (schema.validate(value).error) {
            return {
                error: text
            }
        }

hi i have a big problem with joi i want verify an array with 2 length, first index is hour and maximun 23 value and min 0. second index is minute max is 59 and min is 0.

second rules work well but when i enter for hour like 24 or more joi don't return error, i cant understand what is that!!! for second index of arry i dont have problem and more than 59 and less than 0 work well its just for first index i test first index with string and joi return error but when i use number 60 or more i dont have error! NOTE: sary for bad English


Solution

  • The way you defined your schema, the order of the elements is irrelevant, which means this example will pass:

    [24, 1]
    

    If you want to define your array elements in sequence order, you have to replace the .items with .ordered:

    Joi.array().length(2).ordered(
        Joi.number().integer().max(23).min(0).required(),
        Joi.number().integer().max(59).min(0).required()
    )
    

    This way, the first element is forced to be a value between 0-23, and the second one between 0-59.