Validation Schema
The JSON Storage API allows you to validate documents. To send a schema over the API for validation, include the validation_schema
in the request body when creating or updating a document or documents_validation_schema
in case of a bucket.
A Validation Schema is a JSON object that defines the structure of the data you expect in your document, along with validation rules for each key-value pair. Each key in the schema corresponds to a key in your document, while the associated value is an object representing the validation criteria for that key (We will call it Rule
moving forward).
A Rule can contain following properties
-
type
: string (defaults tostring
) - Indicates the type of validator to use. Recognised type values are:string
: Must be of type string. This is the default type.number
: Must be of type number.boolean
: Must be of type boolean.regexp
: Must be a string that does not generate an exception when creating a new RegExp.array
: Must be an array as determined by Array.isArray.object
: Must be of type object and not Array.isArray.enum
: Value must exist in the enum.date
: Value must be valid as determined by Dateurl
: Must be of type url.email
: Must be of type email.any
: Can be any type.
-
required
: boolean - The required rule property indicates that the field must exist on the source object being validated. -
pattern
: RegExp String - The pattern rule property indicates a regular expression that the value must match to pass validation. -
min
: number - Used on string and array types comparison which is performed against the length property. -
max
: number - Used on string and array types comparison which is performed against the length property. -
len
: number - Used on string and array types comparison which is performed to validate an exact length. -
enum
: array of strings - To validate a value from a list of possible values.Example:
role: { type: 'enum', enum: ['admin', 'user', 'guest'] }
Messages
You can specify a customer error message by using message
property
Example:
{ name: { type: 'string', required: true, message: 'Name is required' } }
Deep Rules
If you need to validate deep object properties you may do so for validation rules that are of the object or array type by assigning nested rules to a fields property of the rule.
Example
address: {
type: 'object',
required: true,
fields: {
street: { type: 'string', required: true },
city: { type: 'string', required: true },
zip: { type: 'string', required: true, len: 8, message: 'invalid zip' },
},
},
name: { type: 'string', required: true },
We use async-validator (opens in a new tab) internally to validate your schema. Schema that you pass is sent to this package as an input.