Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Javascript Library for Schema Validation

License

NotificationsYou must be signed in to change notification settings

acornejo/jjv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A simple and extensible json-schema validator written in javascript. JJVruns in the browser and in the server (through node.js), it has nodependencies and has out-of-the-box AMD support.

JJV implements the latest (v4) JSON Schema Core draft, however due toperformance and security concerns remote schemas are not fetched. Toensure compliance JJV is tested against JSON Schema Test Suite publishedby json-schema.org (and passes all tests). For examples and a detaileddescription of the JSON-schema specification visitjson-schema.org.

JJV is fast! For a detailed performance comparison visit z-schema'sbenchmarkswebsite, which compares various javascript JSON schema validators.

Basic Usage

In the most basic usage an environment must be created, and one or morenamed schemas are registered in the environment (it is also possible toregister schemas with remote URI's in the same way). Javascriptobjects can then be validated against any registered schema.

// create new JJV environmentvarenv=jjv();// Register a `user` schemaenv.addSchema('user',{type:'object',properties:{firstname:{type:'string',minLength:2,maxLength:15},lastname:{type:'string',minLength:2,maxLength:25},gender:{type:'string',enum:['male','female']},email:{type:'string',format:'email'},password:{type:'string',minLength:8}},required:['firstname','lastname','email','password']});// Perform validation against an incomplete user object (errors will be reported)varerrors=env.validate('user',{firstname:'John',lastname:'Smith'});// validation was successfulif(!errors){alert('User has been validated.')}else{alert('Failed with error object '+JSON.stringify(errors));}

It is also possible to validate objects against unregistered and/orunnamed schemas by supplying the schema object directly. For example:

varenv=jjv();varerrors=env.validate({type:'object',properties:{x:{type:'number'},y:{type:'number'}},required:['x','y']},{x:20,y:50});

Validation Options

JJV provides options to control the validation of required fields, thehandling of default values, and the handling of additional properties.

OptionDefaultDescription
checkRequiredtrueIf true it reports missing required properties, otherwise it allows missing required properties.
useDefaultfalseIf true it modifies the object to have the default values for missing non-required fields.
useCoercefalseIf true it enables type coercion where defined.
removeAdditionalfalseIf true it removes all attributes of an object which are not matched by the schema's specification.

The defaults can be overridden for the entire environment or on aper-validation basis. For example, to override the checkRequired optionfor the entire environment simply do:

env.defaultOptions.checkRequired=false;

To override the checkRequired option on a per-validation case do:

env.validate('schemaName', object, {checkRequired: false});

Advanced Usage

JJV provides mechanisms to add support for custom types, custom formats,and custom checks.

Custom Types

Support for additional types can be added through theaddTypefunction. For example, a simple implementation of thedate type couldbe the following:

env.addType('date',function(v){return!isNaN(Date.parse(v));});

Custom Formats

It is also possible to add support for additional string formats throughtheaddFormat function. For example, an implementation of thehexadecimal string format (already included) could be as follows:

env.addFormat('hexadecimal',function(v){return(/^[a-fA-F0-9]+$/).test(v);});

Custom Checks

It is possible to add support for custom checks (i.e.,minItems,maxItems,minLength,maxLength, etc.) through theaddCheck function. For example, an implementation for anexactLengthvalidation keyword that supports arrays and strings can be achieved withthe following:

env.addCheck('exactLength',function(v,p){returnv.length===p;});

Custom Type Coercion

JJV allows custom type coercion rules. As an example, supposed that fieldswhich are declared with as typeinteger are sometimes encoded as a string.Type coercion allows you to specify that all types declared asinteger shouldbe cast/coerced to aninteger before performing validation.

env.addTypeCoercion('integer',function(x){returnparseInt(x,10);});

Recall to set the optionuseCoerce totrue to enable this feature.

$data v5 proposal

JJV supports the$data spec proposed for draft 5 of json-schema,complete with relative and absolute JSON pointers.

For information on how to use these feature see the proposal here:

$data-proposal.

About

Javascript Library for Schema Validation

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp