npm joi with null, undefined, empty values and a d

2019-09-16 10:20发布

问题:

I am using older version of npm module joi => 10.2.2 and i am trying to figure out how can i build the schema so empty, null, undefined values are allowed with a default value.

This works https://github.com/hapijs/joi/issues/516

var schema = joi.object().keys({a:[joi.string().optional(), joi.allow(null)]})

but i don't know how to specify a default value with this.

What i am looking for is this https://github.com/hapijs/joi/issues/1066 (version v10.5.2) but with the syntax of older version of joi.

回答1:

empty() is available in joi 10.2.2. The issue you referenced is just a documentation change.

const joi = require('joi');

const schema = joi.object().keys({
    a: joi.string().optional().allow(null).allow('').empty('').default('default value')
});

let t = {
    a: ''
};

let result = joi.validate(t, schema);

console.log(result);
// { error: null, value: { a: 'default value' } }


标签: node.js npm joi