use*_*330 5 string validation joi
我正在将Hapi.js框架与Joi一起用于数据验证。我正在尝试使用Joi验证JSON文件。我已经定义了一个架构,并且想要检查JSON文件是否具有我的架构中的所有字段。
一些字符串字段可以为空。在我的架构文件中,当我定义min为时0,它是name必填字段。
我正在使用以下架构:
module.exports = {
"name": { "type": "string", "min": 0, "max": 30},
"age": { "type": "number", "min": 1, "max": 36},
"dob": { "type": "string", "min": 0, "max": 100 }
}
Run Code Online (Sandbox Code Playgroud)
如何修改此架构以处理空字符串?
如果要允许空字符串,则需要使用明确允许它们joi.string().allow('')。
var joi = require('joi');
var schema = joi.object().keys({
name: joi.string().min(0).allow('').allow(null),
age: joi.number().min(1).max(36),
dob: joi.string().min(0).max(100)
});
var obj = {
name: '',
age: '18',
dob: '11/11/2998'
};
var result = joi.validate(obj, schema);
console.log(JSON.stringify(result, null, 2));
Run Code Online (Sandbox Code Playgroud)
使用后,上述架构的输出joi.describe为:
{
"type": "object",
"children": {
"name": {
"type": "string",
"valids": [
"",
null
],
"rules": [
{
"name": "min",
"arg": 0
}
]
},
"age": {
"type": "number",
"invalids": [
null,
null
],
"rules": [
{
"name": "min",
"arg": 1
},
{
"name": "max",
"arg": 36
}
]
},
"dob": {
"type": "string",
"invalids": [
""
],
"rules": [
{
"name": "min",
"arg": 0
},
{
"name": "max",
"arg": 100
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)