我有一个 url 值,它只能接受空值和字符串 uri 值,并且 uri 值不能为空,我尝试了几种实现,但没有成功。我使用的 AJV 验证库版本号为 6.12.6。 这些是我的尝试
agreementURL: {
"type": ["string", "null"],
"if": {
"type": "string"
},
"then": {
"format": "uri",
}
},
在 ajv 模式文件中,我们可以根据我们的要求定义一个函数,因此为了解决这个问题,我创建了一个允许 null 和字符串 uri 格式的函数。
ajv.addKeyword('isAllowNullAndURI', {
type: 'string',
validate: function(schema, data) {
if (data === null) {
return true;
}
if (typeof data === 'string' && data.match(/^(?:\w+:)?\/\/[^\s.]+\.\S/)) {
return true;
}
return false;
},
errors: false,
});
agreementReportURL: {
type : ['string','null'],
format:'uri',
isNotEmpty:true,
isAllowNullAndURI:true
},