# z-schema

[ z-schema npm 地址](https://www.npmjs.com/package/z-schema)

[z-schema github地址](https://github.com/zaggino/z-schema)

JavaScript编写的 JSON Schema 验证器用于 `NodeJS`和浏览器。

> version 3也在可以在浏览器中运行，你可以自己[在这](https://rawgit.com/zaggino/z-schema/master/test/SpecRunner.html)运行测试

## Topics

* [用法（Usage）](https://github.com/zaggino/z-schema#usage)
* [特征（Features）](https://github.com/zaggino/z-schema#features)
* [选项（Options）](https://github.com/zaggino/z-schema#options)
* [基准点（Benchmarks）](https://github.com/zaggino/z-schema#benchmarks)

## 用法（Usage）

验证器将尝试在可能的速度下执行同步验证，但在必要时支持异步回调。

### CLI:

```javascript
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:

```javascript
var ZSchema = require("z-schema");
var options = ... // see below for possible option values
var validator = new ZSchema(options);
```

### 同步模式：

```javascript
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();
...
```

### 异步模式：

```javascript
validator.validate(json, schema, function (err, valid) {
    ...
});
```

## Browser:

```javascript
<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`错误。

```javascript
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`特性：

```javascript
ZSchema.setSchemaReader(function (uri) {
    var someFilename = path.resolve(__dirname, "..", "schemas", uri + ".json");
    return JSON.parse(fs.readFileSync(someFilename, "utf8"));
});
```

## 特征

* [Validate against subschema](https://github.com/zaggino/z-schema#validate-against-subschema)
* [Compile arrays of schemas and use references between them](https://github.com/zaggino/z-schema#compile-arrays-of-schemas-and-use-references-between-them)
* [Register a custom format](https://github.com/zaggino/z-schema#register-a-custom-format)
* [Automatic downloading of remote schemas](https://github.com/zaggino/z-schema#automatic-downloading-of-remote-schemas)
* [Prefill default values to object using format](https://github.com/zaggino/z-schema#prefill-default-values-to-object-using-format)
* [Define a custom timeout for all async operations](https://github.com/zaggino/z-schema#asynctimeout)
* [Disallow validation of empty arrays as arrays](https://github.com/zaggino/z-schema#noemptyarrays)
* [Disallow validation of empty strings as strings](https://github.com/zaggino/z-schema#noemptystrings)
* [Disallow schemas that don't have a type specified](https://github.com/zaggino/z-schema#notypeless)
* [Disallow schemas that contain unrecognized keywords and are not validated by parent schemas](https://github.com/zaggino/z-schema#noextrakeywords)
* [Assume additionalItems/additionalProperties are defined in schemas as false](https://github.com/zaggino/z-schema#assumeadditional)
* [Force additionalItems/additionalProperties to be defined in schemas](https://github.com/zaggino/z-schema#forceadditional)
* [Force items to be defined in array type schemas](https://github.com/zaggino/z-schema#forceitems)
* [Force minItems to be defined in array type schemas](https://github.com/zaggino/z-schema#forceminitems)
* [Force maxItems to be defined in array type schemas](https://github.com/zaggino/z-schema#forcemaxitems)
* [Force minLength to be defined in string type schemas](https://github.com/zaggino/z-schema#forceminlength)
* [Force maxLength to be defined in string type schemas](https://github.com/zaggino/z-schema#forcemaxlength)
* [Force properties or patternProperties to be defined in object type schemas](https://github.com/zaggino/z-schema#forceproperties)
* [Ignore remote references to schemas that are not cached or resolvable](https://github.com/zaggino/z-schema#ignoreunresolvablereferences)
* [Ignore case mismatch when validating enum values](https://github.com/zaggino/z-schema#enumCaseInsensitiveComparison)
* [Only allow strictly absolute URIs to be used in schemas](https://github.com/zaggino/z-schema#stricturis)
* [Turn on z-schema strict mode](https://github.com/zaggino/z-schema#strictmode)
* [Set validator to collect as many errors as possible](https://github.com/zaggino/z-schema#breakonfirsterror)
* [Report paths in errors as arrays so they can be processed easier](https://github.com/zaggino/z-schema#reportpathasarray)

### 验证 subschema

如果由于任何原因不想使用引用，将schema分割为多个schema，则可以在验证时使用`schemaPath`选项：

```javascript
var valid = validator.validate(cars, schema, { schemaPath: "definitions.car.definitions.cars" });
```

在 [test](https://github.com/zaggino/z-schema/blob/master/test/spec/schemaPathSpec.js) 中查看更多细节。

### 编译schemas数组并使用它们之间的引用

可以使用验证器编译具有它们之间的引用的schema数组 ， 然后对其中一个schema进行验证。

```javascript
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响应：

```javascript
ZSchema.registerFormat("xstring", function (str) {
    return str === "xxx";
});
```

还支持异步格式验证器，它们应该接受两个参数、值和它们需要响应的回调：

```javascript
ZSchema.registerFormat("xstring", function (str, callback) {
    setTimeout(function () {
        callback(str === "xxx");
    }, 1);
});
```

### 帮助检查已注册的格式的Help方法

```javascript
var registeredFormats = ZSchema.getRegisteredFormats();
//registeredFormats will now contain an array of all formats that have been registered with z-schema
```

### 远程schemas的自动下载

远程模式的自动下载已经从3.x版本中移除，但是仍然可以使用一些额外的代码，有关这方面的更多信息，请参阅[此测试](https://github.com/zaggino/z-schema/blob/master/test/spec/AutomaticSchemaLoadingSpec.js)。

### 使用格式预填充默认值到对象

使用格式，您可以预先将选择的值填充到这样的对象中：

```javascript
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`错误导致验证失败之前，在等待异步任务（如异步格式验证器）执行验证时，应该使用这个时间限制。

```javascript
var validator = new ZSchema({
    asyncTimeout: 2000
});
```

### noEmptyArrays

当为true时，验证器将假定任何数组中的项的最小计数为1，除非`minItems: 0`被显式定义。

```javascript
var validator = new ZSchema({
    noEmptyArrays: true
});
```

### noEmptyStrings

如果为true，则验证器假定任何字符串的传递字符串类型验证的最小长度为1，除非`minLength: 0`是显式定义的。

```javascript
var validator = new ZSchema({
    noEmptyStrings: true
});
```

### noTypeless

如果为true，则验证器将对没有指定期望的对象类型的schemas进行验证失败。

```javascript
var validator = new ZSchema({
    noTypeless: true
});
```

### noExtraKeywords

当为true时，验证器将无法验证使用JSON Schema规范中未定义的关键字、且未在`$schema`属性中提供父schema来验证schema。

```javascript
var validator = new ZSchema({
    noExtraKeywords: true
});
```

## assumeAdditional

当为true时，验证器假设`additionalItems/additionalProperties`被定义为false，因此您不必手动修复所有`schemas`。

```javascript
var validator = new ZSchema({
    assumeAdditional: true
});
```

当为一个数组时，验证器假设`additionalItems/additionalProperties`被定义为false，但是允许一些属性通过。

```javascript
var validator = new ZSchema({
    assumeAdditional: ["$ref"]
});
```

### forceAdditional

当为true时，验证器不验证`schemas`，其中`additionalItems/additionalProperties`应该定义为true或false。

```javascript
var validator = new ZSchema({
    forceAdditional: true
});
```

### forceItems

如果为true，则验证程序不验证schemas中`item`没有为`array`类型的schemas。这是为了避免通过数组定义传递任何内容。

```javascript
var validator = new ZSchema({
    forceItems: true
});
```

### 更多的参数参见[链接](https://github.com/zaggino/z-schema)

## 基准点（Benchmarks）

那么它如何与version 2.x和其他版本相比呢？

注意:这些测试纯粹是面向对象的，它们不考虑任何验证器的额外特性

[rawgithub.com/zaggino/z-schema/master/benchmark/results.html](https://rawgithub.com/zaggino/z-schema/master/benchmark/results.html)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://microservice-nodejs.shujuwajue.com/dan-yuan-ce-shi-xiang-guan-mo-kuai/z-schema.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
