Joi: Trying to get default value for null or empty for joi.string()

Created on 11 Jul 2018  路  6Comments  路  Source: sideway/joi

I want a default value for a Joi object if the value is empty or null

config(Joi) { 
       return Joi.object({ 
         enabled: Joi.boolean().default(true), 
         url: Joi.string().allow('').allow(null).default("xyz"),
         jsFilterFunction: Joi.string.allow('').allow(null).default("abc")
       }).default(); 
     }

Trying the above code gives me the following error.

TypeError: Joi.string.allow is not a function

[Edited by Wes to add the code block formatting]

support

Most helpful comment

Without the allow but yes, use empty. Case closed I think.

All 6 comments

You have a typo in your jsFilterFunction property

It should be Joi.string().allow('') instead of Joi.string.allow('') (missing the string method call parens).

Aside from that, your general approach should be fine. You shouldn't need the .default() on the object().default() call though.

const schema = Joi.object({
    enabled: Joi.boolean().default(true),
    url: Joi.string().allow('', null).default('xyz'),
    jsFilterFunction: Joi.string().allow('', null).default("abc")
});

schema.validate({});
// value: { enabled: true, url: 'xyz', jsFilterFunction: 'abc' }

If you are also wanting your url and jsFilterFunction properties to stamp in the default values when null or '' are present, you'll need to modify each property from:

Joi.string().allow('', null).default('xyz')

to

Joi.string().allow('', null).empty(['', null]).default('xyz')

let schema = Joi.string().allow('', null).default('xyz');

schema.validate(null);
// value: null

schema = Joi.string().allow('', null).empty(['', null]).default('xyz');
schema.validate(null);
// value: 'xyz'

Without the allow but yes, use empty. Case closed I think.

Worked for me Thanks @WesTyler

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.

Was this page helpful?
0 / 5 - 0 ratings