<script src="bower_components/jsen/dist/jsen.min.js"></script><script> var validate = jsen({ type: 'string' }); // under window.jsen var valid = validate('some value'); // true</script>
Validation works by passing a JSON schema to build a validator function that can be used to validate a JSON object.
The validator builder function (jsen) throws an error if the first parameter is not a schema object:
try { // cannot use this string as a schema jsen('not a valid schema');}catch (e) { console.log(e);}
jsen will not throw an error if the provided schema is not compatible with the JSON-schema version 4 spec. In this case, as per the spec, validation will always succeed for every schema keyword that is incorrectly defined.
// this will not throw, but validation will be incorrectvar validate = jsen({ type: 'object', properties: ['string', 'number'] });// validation erroneously passes, because keyword `properties` is ignoredvar valid = validate({}); // true
If you need to validate your schema object, you can use a reference to the JSON meta schema. Internally, jsen will recognize and validate against the metaschema.
var validateSchema = jsen({"$ref": "http://json-schema.org/draft-04/schema#"});var isSchemaValid = validateSchema({ type: 'object' }); // trueisSchemaValid = validateSchema({ type: 'object', properties: ['string', 'number']});// false, because properties is not in correct format
Performance & Benchmarks
JSEN uses dynamic code generation to produce a validator function that the V8 engine can optimize for performance. Following is a set of benchmarks where JSEN is compared to other JSON Schema validators for node.
JSEN supports a few built-in formats, as defined by the JSON Schema spec:
date-time
uri
email
ipv4
ipv6
hostname
These formats are validated against string values only. As per the spec, format validation passes successfully for any non-string value.
var schema = { format: 'uri' }, validate = jsen(schema);validate('invalid/uri'); // false - format validation kicks in for stringsvalidate({}); // true - does not kick in for non-strings
Custom Formats
JSEN additionally supports custom format validation. Custom formats are passed in options.formats as a second argument to the jsen validator builder function.
a function (value, schema) that must return a truthy value if validation passes
Unlike built-in format validators, custom format validators passed in the options are run for all data types, not only strings. This allows implementing custom validation behavior for arrays and objects in scenarios, where it is not possible or practical to use only JSON Schema keywords for validation rules.
Custom format validation runs after all built-in keyword validators. This means that an error in any previous keyword validator will stop execution and any custom format validators won't run.
External Schemas
You can use references to external schema objects through the $ref keyword. You pass external schemas in the options.schemas object:
Although JSEN does not automatically fetch remote schemas by making HTTP requests, you can fetch and provide them through the schemas option by giving their URIs as object keys.
The validator function (the one called with the object to validate) provides an errors array containing all reported errors in a single validation run.
var validate = jsen({ type: 'string' });validate(123); // falseconsole.log(validate.errors)// Output: [{ path: '', keyword: 'type' }]// path - deep (dot-delimited) path to the property that failed validation// keyword - the JSON schema keyword that failed validationvalidate('abc'); // true// Output: []
The errors array may contain multiple errors from a single run.
When the additionalProperties keyword fails validation, the respective error object contains a key by the same name, specifying the property name that was found in the validated object, but was fobidden in the schema:
Custom error messages are assigned to error objects by path, meaning multiple failed JSON schema keywords on the same path will show the same custom error message.
The requiredMessage is assigned to errors coming from the required and dependencies keywords. For all other validation keywords, the invalidMessage is used.
Custom Errors for Keywords
You can assign custom error messages to keywords through the messages object in the JSON schema.
var schema = { type: 'object', messages: { type: 'Invalid data type where an object is expected' }}var validate = jsen(schema);validate('this is a string, not an object');console.log(validate.errors);/* Output:[ { path: '', keyword: 'type', message: 'Invalid data type where an object is expected' } ]*/
NOTE: The following keywords are never assigned to error objects, and thus do not support custom error messages: items, properties, patternProperties, dependecies (when defining a schema dependency) and allOf.
Greedy Validation
For performance, by default, JSEN returns the first encountered error and bails out any further execution.
With the options.greedy flag passed to the builder function, the compiled validator will try to validate as much as possible, providing more info in the errors array.
JSEN can collect default values from the schema. The build(initial, options) method in the dynamic validator function recursively walks the schema object and compiles the default values into a single object or array.
By default, the build function creates a copy of the initial data object. You can opt to modify the object in-place by passing { copy: false } as a second argument.
The JSON schema spec allows additional properties by default. In many cases, however, this default behavior may be undesirable, forcing developers to specify additionalProperties: false everywhere in their schema objects. JSEN's build function can filter out additional properties by specifying { additionalProperties: false } as a second argument.
var validate = jsen({ properties: { foo: {}, bar: {} }});var initial = { foo: 1, bar: 2, baz: 3};initial = validate.build(initial, { additionalProperties: false });console.log(initial); // { foo: 1, bar: 2 }
When both options.additionalProperties and schema.additionalProperties are specified, the latter takes precedence.
var validate = jsen({ additionalProperties: true, properties: { foo: {}, bar: {} }});var initial = { foo: 1, bar: 2, baz: 3};initial = validate.build(initial, { additionalProperties: false });console.log(initial); // { foo: 1, bar: 2, baz: 3 }
NOTE: When { additionalProperties: false, copy: false } is specified in the build options, any additional properties will be deleted from the initial data object.
In some scenarios, you may want to disallow additional properties in the schema, but still keep them when gathering default values with build(). This may be required, for example, when you want to explicitly fail validation and display a message to the user, listing any excessive properties that are forbidden by the schema. Setting { additionalProperties: 'always' } will prevent the build() function from removing any properties in the initial object.
var schema = { additionalProperties: false, properties: { foo: {} } };var initial = { foo: 1, bar: 2 };var validate = jsen(schema);var withDefaults = validate.build(initial, { additionalProperties: 'always' });// withDefaults has both 'foo' and 'bar' keys
In-Browser Usage
Browser-compatible builds of jsen (with the help of browserify) can be found in the dist folder. These are built with the standalone option of browserify, meaning they will work in node, the browser with globals, and AMD loader environments. In the browser, the window.jsen global object will refer to the validator builder function.
To run the same test suite in the browser, serve the test/index.html page in your node web server and navitate to /test/ path from your browser. The example below uses node-static:
[~/github/jsen] $ npm install -g node-static...[~/github/jsen] $ static .serving "." at http://127.0.0.1:8080# navigate to http://127.0.0.1:8080/test/ in your browser
jsen passes all draft 4 test cases specified by the JSON-Schema-Test-Suite with the exception of zero-terminated float tests.
To contribute to the project, fork the repo, edit and send a Pull Request. Please adhere to the coding guidelines enforced by the jshint and jscs code checkers.