2017-08-25 105 views
4

我正在使用Ajv验证我的JSON数据。我无法找到验证空字符串作为键的值的方法。我尝试使用模式,但它不会抛出适当的消息。使用AJV在json模式中验证空值使用AJV

这里是我的架构

{ 
    "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检查值应包含至少一个字符。但它也允许空的空间。

回答

1

现在在AJV中没有内置选项可以这样做。

1

你可以这样做:

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": "..." 
     } 
    } 
    } 
} 
0

我找到了另一种方式来做到这一点使用 “不” 关键字与 “最大长度”:

{ 
    [...] 
    "type": "object", 
    "properties": { 
    "inputName": { 
     "type": "string", 
     "allOf": [ 
     {"not": { "maxLength": 0 }, "errorMessage": "..."}, 
     {"minLength": 6, "errorMessage": "..."}, 
     {"maxLength": 100, "errorMessage": "..."}, 
     {"..."} 
     ] 
    }, 
    }, 
    "required": [...] 
} 

不幸的是,如果有人用空格填充该字段,它将是有效的,因为空格计为字符。这就是为什么我更喜欢ajv.addKeyword('isNotEmpty',...)方法,它可以在验证之前使用trim()函数。

干杯!