有没有办法为json架构(tv4)设置oneOf
字段失败时的自定义消息?
我看到大约一年前here和here的自定义消息已经打开了一个问题,但有没有办法让这个工作适合这样的事情?
{
"id": "code",
"description": "Schema for request.body - pin for logging into the bank",
"oneOf": [
{
"type": "string",
"pattern": "^.*\\S.*$"
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"pattern": "^(encrypted|not_encrypted)$"
},
"value": {
"type": "string",
"pattern": "^.*\\S.*$"
}
}
}
],
"messages": {
"oneOf": "Code does not match schema"
}
}
与仅查看Data does not match any schemas from \"oneOf\"
相反,您可以看到Code does not match schema
[编辑]
我正在尽可能地阅读tv4代码,我看到很多关于自定义错误消息和代码的信息,例如。
defineError: function (codeName, codeNumber, defaultMessage) {
if (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) {
throw new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES');
}
if (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) {
throw new Error('Code number must be an integer > 10000');
}
if (typeof ErrorCodes[codeName] !== 'undefined') {
throw new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]);
}
if (typeof ErrorCodeLookup[codeNumber] !== 'undefined') {
throw new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber);
}
ErrorCodes[codeName] = codeNumber;
ErrorCodeLookup[codeNumber] = codeName;
ErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage;
for (var langCode in languages) {
var language = languages[langCode];
if (language[codeName]) {
language[codeNumber] = language[codeNumber] || language[codeName];
}
}
},
我可以通过一个简单的行tv4.defineError('MY_CUSTOM_CODE_ERROR', 999999, "Hello World, you have a custom code error");
添加我自己的错误及其自己的状态代码(通过此函数)。如何将此错误与此特定json架构相关联?如果我完全在错误的地方,那么有人也会指出这一点
答案 0 :(得分:1)
我偶然发现了GitHub的帖子,试图找到一个解决方案,用于向&#34; anyOf&#34;,&#34; oneOf&#34;添加自定义消息。条款。这对我有用: 见 here
tv4.setErrorReporter(function (error, data, schema) {
// Last component of schemaPath, which *most* of the time is the keyword!
var lsP = error.schemaPath.split('/').splice(-1);
return schema.messages && schema.messages[lsP];
});
,您的架构定义如下:
{
"id": "code",
"description": "Schema for request.body - pin for logging into the bank",
"oneOf": [
{
"type": "string",
"pattern": "^.*\\S.*$"
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"pattern": "^(encrypted|not_encrypted)$"
},
"value": {
"type": "string",
"pattern": "^.*\\S.*$"
}
}
}
],
"messages": {
"oneOf": "Code does not match schema"
}
}