npm joi with null, undefined, empty values and a default value

亡梦爱人 提交于 2019-12-12 06:23:54

问题


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' } }


来源:https://stackoverflow.com/questions/44404799/npm-joi-with-null-undefined-empty-values-and-a-default-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!