我正在使用 Ajv 来验证我的 JSON 数据。我无法找到一种方法来验证空字符串作为键的值。我尝试使用模式,但它没有抛出适当的消息。
这是我的架构
{
"type": "object",
"properties": {
"user_name": { "type": "string" , "minLength": 1},
"user_email": { "type": "string" , "minLength": 1},
"user_contact": { "type": "string" , "minLength": 1}
},
"required": [ "user_name", 'user_email', 'user_contact']
}
我正在使用 minLength 来检查该值应至少包含一个字符。但它也允许留出空间。
最佳答案
你可以这样做:
ajv.addKeyword('isNotEmpty', {
type: 'string',
validate: function (schema, data) {
return typeof data === 'string' && data.trim() !== ''
},
errors: false
})
在 json 架构中:
{
[...]
"type": "object",
"properties": {
"inputName": {
"type": "string",
"format": "url",
"isNotEmpty": true,
"errorMessage": {
"isNotEmpty": "...",
"format": "..."
}
}
}
}
关于json - 使用 AJV 在 json 模式中验证空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45888524/