const schema = Joi.object({
a: Joi.string().default('a'),
b: Joi.string()
})
const input = undefined;
const result = Joi.validate(input,schema);
console.log(result)
result is undefined
result must be {a:'a'}
As it's written, the default will only be applied if the value is an object, but the a property is empty:
const schema = Joi.object({
a: Joi.string().default('a'),
b: Joi.string()
})
const input = {};
const result = Joi.validate(input,schema);
console.log(result) // value: { a: 'a' }
If you want this to work for an undefined input for the object you'll need the default on the object itself:
const schema = Joi.object({
a: Joi.string(),
b: Joi.string()
}).default({ a: 'a' });
const input = undefined;
const result = Joi.validate(input,schema);
console.log(result); // value: { a: 'a' }
@westyler so I have to define default twice , and when my object has too many fields its very tedious
If you want to stamp in defaults for undefined for both the parent object
and also the children, then yes. Though you can simplify it with some
schema composition (I can elaborate when I get back to a computer this
evening).
On the note about it being tedious, think about the alternative without
leveraging Joi’s default handling. You would have to check the parent and
then default to an object, then manually write conditional checks for each
field. I personally think that verbose schema are more clear and easily
maintained, but don’t feel like you have to leverage Joi for all of your
business logic :)
On Mon, Jan 21, 2019 at 11:30 AM sm2017 notifications@github.com wrote:
@WesTyler https://github.com/WesTyler so I have to define default twice
, and when my object has too many fields its very tedious—
You are receiving this because you were mentioned.Reply to this email directly, view it on GitHub
https://github.com/hapijs/joi/issues/1706#issuecomment-456149215, or mute
the thread
https://github.com/notifications/unsubscribe-auth/ALl4O9Wg2_H64qh2q41nrG2UcxmIHlK9ks5vFflGgaJpZM4aK1fJ
.
Default has a special case for objects where you can call it without any argument and it will do what you want.
@Marsup your approach works , But I have another issue
var Joi = require("joi")
const schema = Joi.object({
a: Joi.string().default('a'),
b: Joi.string()
}).default()
const input = undefined;
Joi.validate(input,schema,function(err,value){
console.log('err',err)
console.log('value',value)
});
is OK and we have default values for undefined , But I want to extend Joi and
params: { options: Joi.object({
a: Joi.string().default('a'),
b: Joi.string()
}).default()
}
is not works and default is not set
params can also be a Joi.object itself.
Considering it solved, let me know if not.
This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.
Most helpful comment
paramscan also be aJoi.objectitself.