我正在使用express-jsonschema来验证JSON HTTP POST请求的架构。这是模式:
var massiveReportSchema = {
type: 'object',
properties: {
email: {
type: 'string',
required: true
},
author: {
type: 'string',
required: true
},
userId: {
type: 'array',
required: true,
items: {type: 'string'}
}
}
}
我想验证userId
中的每个元素的格式"userId account"
。我想我可以使用正则表达式,但我不知道如何使用。这是一个示例请求的主体:
{
"email": "test.doe@mail.com",
"author": "John Doe",
"userId" : [ "100 500",
"101 default",
"102 600"]
}
您可以使用以下方式验证userId
中的每个元素...
var res = {
"email": "test.doe@mail.com",
"author": "John Doe",
"userId" : [
"100 500",
"101 default",
"105900",
"102 600"
]
};
res.userId.forEach(function(e) {
var result = 'Validating "' + e + '" | Status : ' + /w+sw+/.test(e);
console.log(result);
});
这很简单
var massiveReportSchema = {
type: 'object',
properties: {
email: {
type: 'string',
required: true
},
author: {
type: 'string',
required: true
},
userId: {
type: 'array',
required: true,
items: {type: 'string', pattern: "d+sd+"}
}
}
}
更多信息:
https://spacetelescope.github.io/understanding-json-schema/reference/regular_expressions.html