Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate object constraint in a object using joi?

I am trying object validation with the help of joi. I want to validate object as a constraint inside an object like

let login = {
    value: 0/1,
    slots: [{ label: '', value: '24 hr'}, { label: '', value: '24 hr'}]
}

Here login is an object and inside it slots is also an object. So if I write like the following

const schema = Joi.object().keys({
 value : Joi.number.required(),
 slots : Joi.string.required()
});

would it be correct for object data type or should I replace string data type with object data type? I want to validate object type as a constraint.

like image 694
Swati Dixit Avatar asked Mar 17 '26 08:03

Swati Dixit


1 Answers

Your slots key needs to be an array of objects:

const schema = Joi.object().keys({
    value: Joi.number().required(),
    slots: Joi.array().items(
        Joi.object().keys({
            label: Joi.string().required().allow(''),
            value: Joi.string().required()
        })
    )
})

This way, the following object will be valid:

const obj = {
    value: 1,
    slots: [
        {
            label: '',
            value: '24 hr'
        }
    ]
}
like image 111
soltex Avatar answered Mar 19 '26 21:03

soltex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!