JavaScript编写的 JSON Schema 验证器用于 NodeJS
和浏览器。
version 3也在可以在浏览器中运行,你可以自己 运行测试
Topics
用法(Usage)
验证器将尝试在可能的速度下执行同步验证,但在必要时支持异步回调。
CLI:
Copy npm install --global z-schema
z-schema --help
z-schema mySchema.json
z-schema mySchema.json myJson.json
z-schema --strictMode mySchema.json myJson.json
NodeJS:
Copy var ZSchema = require("z-schema");
var options = ... // see below for possible option values
var validator = new ZSchema(options);
同步模式:
Copy var valid = validator.validate(json, schema);
// this will return a native error object with name and message
var error = validator.getLastError();
// this will return an array of validation errors encountered
var errors = validator.getLastErrors();
...
异步模式:
Copy validator.validate(json, schema, function (err, valid) {
...
});
Browser:
Copy <script type="text/javascript" src="../dist/ZSchema-browser-min.js"></script>
<script type="text/javascript">
var validator = new ZSchema();
var valid = validator.validate("string", { "type": "string" });
console.log(valid);
</script>
远程引用和schemas:
如果您的架构中有一些远程引用,则必须在使用验证器之前下载这些schemas。否则,当试图编译schemas时,将获得UNRESOLVABLE_REFERENCE
错误。
Copy var validator = new ZSchema();
var json = {};
var schema = { "$ref": "http://json-schema.org/draft-04/schema#" };
var valid = validator.validate(json, schema);
var errors = validator.getLastErrors();
// valid === false
// errors.length === 1
// errors[0].code === "UNRESOLVABLE_REFERENCE"
var requiredUrl = "http://json-schema.org/draft-04/schema";
request(requiredUrl, function (error, response, body) {
validator.setRemoteReference(requiredUrl, JSON.parse(body));
var valid = validator.validate(json, schema);
var errors = validator.getLastErrors();
// valid === true
// errors === undefined
}
如果能够同步加载schemas,则可以使用ZSchema.setSchemaReader
特性:
Copy ZSchema.setSchemaReader(function (uri) {
var someFilename = path.resolve(__dirname, "..", "schemas", uri + ".json");
return JSON.parse(fs.readFileSync(someFilename, "utf8"));
});
特征
验证 subschema
如果由于任何原因不想使用引用,将schema分割为多个schema,则可以在验证时使用schemaPath
选项:
Copy var valid = validator.validate(cars, schema, { schemaPath: "definitions.car.definitions.cars" });
编译schemas数组并使用它们之间的引用
可以使用验证器编译具有它们之间的引用的schema数组 , 然后对其中一个schema进行验证。
Copy var schemas = [
{
id: "personDetails",
type: "object",
properties: {
firstName: { type: "string" },
lastName: { type: "string" }
},
required: ["firstName", "lastName"]
},
{
id: "addressDetails",
type: "object",
properties: {
street: { type: "string" },
city: { type: "string" }
},
required: ["street", "city"]
},
{
id: "personWithAddress",
allOf: [
{ $ref: "personDetails" },
{ $ref: "addressDetails" }
]
}
];
var data = {
firstName: "Martin",
lastName: "Zagora",
street: "George St",
city: "Sydney"
};
var validator = new ZSchema();
// compile & validate schemas first, z-schema will automatically handle array
var allSchemasValid = validator.validateSchema(schemas);
// allSchemasValid === true
// now validate our data against the last schema
var valid = validator.validate(data, schemas[2]);
// valid === true
注册自定义格式
你可以注册任何你自己的格式。您的同步验证函数应该始终用boolean响应:
Copy ZSchema.registerFormat("xstring", function (str) {
return str === "xxx";
});
还支持异步格式验证器,它们应该接受两个参数、值和它们需要响应的回调:
Copy ZSchema.registerFormat("xstring", function (str, callback) {
setTimeout(function () {
callback(str === "xxx");
}, 1);
});
帮助检查已注册的格式的Help方法
Copy var registeredFormats = ZSchema.getRegisteredFormats();
//registeredFormats will now contain an array of all formats that have been registered with z-schema
远程schemas的自动下载
使用格式预填充默认值到对象
使用格式,您可以预先将选择的值填充到这样的对象中:
Copy ZSchema.registerFormat("fillHello", function (obj) {
obj.hello = "world";
return true;
});
var data = {};
var schema = {
"type": "object",
"format": "fillHello"
};
validator.validate(data, schema);
// data.hello === "world"
选项(Options)
asyncTimeout
定义一个时间限制,在ASYNC_TIMEOUT
错误导致验证失败之前,在等待异步任务(如异步格式验证器)执行验证时,应该使用这个时间限制。
Copy var validator = new ZSchema({
asyncTimeout: 2000
});
noEmptyArrays
当为true时,验证器将假定任何数组中的项的最小计数为1,除非minItems: 0
被显式定义。
Copy var validator = new ZSchema({
noEmptyArrays: true
});
noEmptyStrings
如果为true,则验证器假定任何字符串的传递字符串类型验证的最小长度为1,除非minLength: 0
是显式定义的。
Copy var validator = new ZSchema({
noEmptyStrings: true
});
noTypeless
如果为true,则验证器将对没有指定期望的对象类型的schemas进行验证失败。
Copy var validator = new ZSchema({
noTypeless: true
});
当为true时,验证器将无法验证使用JSON Schema规范中未定义的关键字、且未在$schema
属性中提供父schema来验证schema。
Copy var validator = new ZSchema({
noExtraKeywords: true
});
assumeAdditional
当为true时,验证器假设additionalItems/additionalProperties
被定义为false,因此您不必手动修复所有schemas
。
Copy var validator = new ZSchema({
assumeAdditional: true
});
当为一个数组时,验证器假设additionalItems/additionalProperties
被定义为false,但是允许一些属性通过。
Copy var validator = new ZSchema({
assumeAdditional: ["$ref"]
});
forceAdditional
当为true时,验证器不验证schemas
,其中additionalItems/additionalProperties
应该定义为true或false。
Copy var validator = new ZSchema({
forceAdditional: true
});
forceItems
如果为true,则验证程序不验证schemas中item
没有为array
类型的schemas。这是为了避免通过数组定义传递任何内容。
Copy var validator = new ZSchema({
forceItems: true
});
基准点(Benchmarks)
那么它如何与version 2.x和其他版本相比呢?
注意:这些测试纯粹是面向对象的,它们不考虑任何验证器的额外特性