I am using the Hapi.js framework along with Joi for data validation. I am trying to validate a JSON file using Joi. I have defined a schema and wanted to check whether the JSON file had all the fields from my schema.
Some of the string fields can be empty. In my schema file when I defined min
as 0
, it is saying name
is a required field.
I am using the schema below:
module.exports = {
"name": { "type": "string", "min": 0, "max": 30},
"age": { "type": "number", "min": 1, "max": 36},
"dob": { "type": "string", "min": 0, "max": 100 }
}
How can I modify this schema to handle empty strings?
If you want to allow empty strings, you need to explicitly allow them with 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));
The output of the above schema after using joi.describe
is:
{
"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
}
]
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With