Reputation: 445
Joi validation does not support modification of existing object keys.
I am using Joi validation for parent and child classes. The validation for the parent is the base validation for all children, but each child has specific restrictions or additional fields. I want to be able to just take my parent Joi object and be able to modify existing keys to fit certain restrictions.
//Declare base class with an array at most 10 elements
const parent = {
myArray: Joi.array().max(10)
}
//Now declare child with minimum 1 array value
const child = parent.append({
foo: Joi.string(),
myArray: Joi.array().min(1).required()
})
The above code works as expected - meaning the child object does not keep the .limit(10) restriction applied to the parent. But, I want it such that it does. I'm sure append is not the right function to use here, but I am not sure of how to do this. I want my resulting child validation to look like:
const child = {
foo: Joi.string(),
myArray: Joi.array().max(10).min(1).required()
}
Upvotes: 0
Views: 7025
Reputation: 3321
Have you tried:
const child = parent.append({
foo: Joi.string(),
myArray: parent.myArray.min(1).required()
});
Just tried:
const Joi = require('joi');
const parent = {
x: Joi.array().max(10).required()
};
const child = Object.assign({}, parent, {
x: parent.x.min(1).required(),
y: Joi.string()
});
Joi.validate({
x: [],
y: 'abc'
}, child); // fails as .min(1) not satisfied
Joi.validate({
x: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
y: 'abc'
}, child); // fails as .max(10) not satisfied
Joi.validate({
x: [1],
y: 'abc'
}, child); // OK
Tried with a fresh npm i joi
(package says: "joi": "^14.3.1"
), on Node v8.10.0. Or maybe the example you gave is too trivial to reflect your real scenario?
Upvotes: 1