Validate Fields
A simple yet powerful JSON schema validator
Install
npm install validate-fields
Usage
Basic
let validate = schema = name: String age: 'uint' value = name: 'Ann' age: 27 // Validate the value against the schema definitionif console else console
validate
throws if it could not understand the schema and returns false if the schema is ok but the value doesn't match the schema.
validate.lastError
, validate.lastErrorMessage
and validate.lastErrorPath
will let you know about the validation error cause
See the list of valid values for the schema bellow
Pre-parsing
// Parse the schema once and store itlet schema = validate // an array of non-empty strings // Set express route// app here is an express instance, used only to ilustrate this example (not part of this module!)app
This way is recommended because if the schema definition is invalid, validate.parse()
will throw early and schema.validate()
won't throw. You also gain in speed!
Escaping HTML
HTML strings can be escaped by sending one more argument to validate
:
let v = 'html>'v0 === 'html>' v0 === 'html>'
Or, using pre-parsing
let v = 'html>'validatev0 === 'html>'
Strict matching
By default, extra keys are not considered errors:
// true
This can be changed with the strict
option:
// false
Standard types
Hash map (object)
Example: {a: Number, 'b?': String, c: {d: 'int'}}
Keys that end in '?'
are optional (b
, in the example above). All others must be present and must not empty. Empty is null
or undefined
; for strings, ''
is also considered empty.
If a value is optional and is empty it will be removed. Example:
let obj = a: '' b: null // trueobj // {}
Optional fields may declare a default value to use in its place when empty. Example:
let obj = {} // trueobj // {a: 12, b: [], c: 'hi'}
The value after the =
character must be a valid JSON.
Array
Example: {books: [{title: String, author: String}]}
Other types
Number
: a doubleString
: a stringObject
: any non-null objectArray
: any arrayBoolean
Date
: any date string accepted by Date constructor (ISO strings are better though)'*'
: anything'number(-3.5,10)'
: a numberx
with-3.5 <= x <= 10
'number(-3.5,)'
: a numberx
with-3.5 <= x
'number(,10)'
: a numberx
withx <= 10
'numeric'
: a double value encoded in a string'numeric(<...>)'
: like'number(<...>)'
, but for numeric strings'int'
: an integer between -2^51 and 2^51 (safe integer)'int(-3,10)'
: an integer between -3 and 10. Lower and upper bounds are optional'numericInt'
: like'int'
, but for numeric strings'uint'
: a natural number less than 2^51'uint(3,10)'
: a natural number between 3 and 10. Lower and upper bounds are optional'numericUint'
: like'int'
, but for numeric strings'string(17)'
: a string with exactly 17 chars'string(,100)'
: at most 100 chars'string(8,)'
: at least 8 chars'string(8,100)'
: at most 100, at least 8'hex'
: a hex string (even number of hex-chars)'hex(12)'
: a hex-string with exactly 12 hex-chars (that is, 6 bytes)'base64'
: a base64 string, with valid padding'id'
: a mongo objectId as a 24-hex-char string'email'
: a string that looks like an email address'in(cat, dog, cow)'
: a string in the given set of strings'numberIn(3, 1.4, -15)'
: a number in the given set of values'numericIn(<...>)'
: like'numberIn(<...>)'
, but for numeric strings/my-own-regex/
: a string that matches the custom regexp
Custom types
The simplest way to define your own type is like this:
validatevalidate // falsevalidatelastError // 'I was expecting a value in first' // true
Typedef works as a simple alias (like in C)
Every time you call require('validate-fields')()
a new context is created. Each context is isolated from each other. Types defined in one context do not conflict with other contexts.
If you need more power, you can create the type from scratch and define every detail about the validation.
In the example bellow, we create a type defined by 'divBy3' that matches JSON numbers. The third param is the check function, that should throw when the value is invalid. It may return a new value, that will replace the original value in the object
validate let obj = n: 12 // trueobjn // 4
In the example bellow, we implement the general case of the above. Instead of a fixed string (divBy3) we define a syntax like 'divBy(n)'
where n
is a number. The "argument" list is sent as the third parameter to the check function.
validate // false // true
See more examples in the folder types
. All core types are defined there
Finally, you can extend a type by providing pre and post hooks:
validate validate
Pre-hooks will be executed before the base type checks. Post-hooks will be run afterwards.
Interchangeable format
A parsed Field
can be serialized to JSON with JSON.stringify()
:
let fields = validateJSON // '{"name":"$String","age":"uint","birth?":"$Date"}'
Note that custom types can't be serialized, they are replaced by their JSON-type:
let fields = validate // defined aboveJSON // '{"myType":"$Number"}'
To get back a Field
instance, JSON.parse()
should be used with a reviver and the result then parsed:
let serializedFields = '{"name":"$String","age":"uint","birth?":"$Date"}'let definition = JSON // {name: String, age: 'uint', 'birth?': Date}let fields = validate fields // true
JSON Schema
A parsed Field
can be exported as JSON Schema:
let fields = validatefields/* { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer', minimum: 0 }, birth: { type: 'string', format: 'date-time' } }, required: ['name', 'age']} */
Partial validation
A schema can be used for validating only a subset of fields, for example:
let schema = validateschema // falseschema // true
This is useful when fields in the value can be dynamically selected, like in an endpoint when the caller only cares about two or three fields from a normally bigger schema.
Multiple paths should be passed as elements of the options.partial
array. Paths can also recurse into inner properties:
// true
In arrays, partial paths enumerate over its elements:
// falsevalidatelastError // I was expecting number and you gave me string in table.rows.1.cells.1.value
Custom values should implement partial validation accordingly, using the value received over options._partialTree
. Example:
validate
In strict mode, any field in the value not listed in the partial will result in an error. Likewise, any field in the partial not in the schema will result in an error.