github.com/kaptinlin/jsonschema@v0.4.6/examples/custom-formats/README.md (about) 1 # Custom Formats Example: OpenAPI 3.0 Support 2 3 This example demonstrates how to extend the `jsonschema` library to support the built-in formats defined in the OpenAPI 3.0 specification. 4 5 The core library does not include these formats by default to remain lightweight and specification-agnostic. However, you can easily add them using the `RegisterFormat` method. 6 7 ## Features Demonstrated 8 9 1. **Implementing Format Validators**: Shows how to write validation functions for formats like `int32`, `int64`, `float`, `double`, `byte`, etc. 10 2. **Registering Custom Formats**: Uses `RegisterFormat` to add the OpenAPI formats to a `Compiler` instance. 11 3. **Type-Specific Validation**: Associates formats with specific JSON Schema types (e.g., `int32` with `"number"`). 12 4. **Schema Validation**: Validates a JSON object against a schema that uses these custom-registered OpenAPI formats. 13 14 ## How It Works 15 16 The `main.go` file contains: 17 - Validation functions (e.g., `validateInt32`, `validateInt64`). 18 - A helper function `registerOpenAPIFormats` that registers all the formats. 19 - A `main` function that uses these formats to validate a sample schema. 20 21 ## Usage 22 23 To run the example and see the validation in action: 24 25 ```bash 26 go run main.go 27 ``` 28 29 The output will show the results of validating both a valid and an invalid data structure against the schema. 30 31 ## Custom Formats in the Example 32 33 ### 1. Identifier Format (String) 34 - **Type**: `string` 35 - **Pattern**: `^[a-zA-Z_][a-zA-Z0-9_]*$` 36 - **Description**: Valid programming language identifier 37 38 ### 2. Percentage Format (Number) 39 - **Type**: `number` 40 - **Range**: 0-100 41 - **Description**: Percentage value validation 42 43 ### 3. Port Format (Integer) 44 - **Type**: `integer` 45 - **Range**: 1-65535 46 - **Description**: Valid network port number 47 48 ## OpenAPI 3 Built-in Formats 49 50 The library automatically registers these OpenAPI 3.0/3.1 formats: 51 52 - `int32`: 32-bit signed integer 53 - `int64`: 64-bit signed integer 54 - `float`: IEEE-754 single precision 55 - `double`: IEEE-754 double precision 56 - `byte`: Base64 encoded string 57 - `binary`: Binary data (for file uploads) 58 - `password`: Password field (UI hint) 59 60 ## API Reference 61 62 ### Register Custom Format 63 ```go 64 compiler.RegisterFormat(name, validator, typeName...) 65 ``` 66 67 - `name`: Format name to use in schemas 68 - `validator`: Function that returns true if value matches format 69 - `typeName`: Optional, JSON Schema type ("string", "number", etc.) to which the format applies 70 71 ### Unregister Custom Format 72 ```go 73 compiler.UnregisterFormat(name) 74 ``` 75 76 - `name`: The name of the format to remove. 77