{"id":13527059,"url":"https://github.com/molnarg/js-schema","last_synced_at":"2025-04-12T19:50:29.280Z","repository":{"id":3407276,"uuid":"4457488","full_name":"molnarg/js-schema","owner":"molnarg","description":"Simple and intuitive schema validator","archived":false,"fork":false,"pushed_at":"2016-11-23T19:37:02.000Z","size":829,"stargazers_count":388,"open_issues_count":21,"forks_count":43,"subscribers_count":22,"default_branch":"master","last_synced_at":"2024-10-29T23:30:52.227Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://molnarg.github.com/js-schema/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":"Unmaintained","scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/molnarg.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-05-26T20:09:05.000Z","updated_at":"2024-09-24T07:25:23.000Z","dependencies_parsed_at":"2022-09-21T13:00:41.378Z","dependency_job_id":null,"html_url":"https://github.com/molnarg/js-schema","commit_stats":null,"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/molnarg%2Fjs-schema","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/molnarg%2Fjs-schema/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/molnarg%2Fjs-schema/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/molnarg%2Fjs-schema/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/molnarg","download_url":"https://codeload.github.com/molnarg/js-schema/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248625501,"owners_count":21135513,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T06:01:40.111Z","updated_at":"2025-04-12T19:50:29.253Z","avatar_url":"https://github.com/molnarg.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","JSON Schema Tools"],"sub_categories":[],"readme":"js-schema\n=========\n\njs-schema is a new way of describing object schemas in JavaScript. It has a clean and simple syntax,\nand it is capable of serializing to/from the popular JSON Schema format. The typical use case is\ndeclarative object validation.\n\n**Latest release**: 1.0.1 (2015/05/06)\n\nFeatures\n========\n\nDefining a schema:\n\n```javascript\nvar Duck = schema({              // A duck\n  swim : Function,               //  - can swim\n  quack : Function,              //  - can quack\n  age : Number.min(0).max(5),    //  - is 0 to 5 years old\n  color : ['yellow', 'brown']    //  - has either yellow or brown color\n});\n```\n\nThe resulting function (`Duck`) can be used to check objects against the declared schema:\n\n```javascript\n// Some animals\nvar myDuck = { swim : function() {}, quack : function() {}, age : 2, color : 'yellow' },\n    myCat =  { walk : function() {}, purr  : function() {}, age : 3, color : 'black'  },\n    animals = [ myDuck, myCat, {}, /*...*/ ];\n\n// Simple checks\nconsole.log( Duck(myDuck) ); // true\nconsole.log( Duck(myCat)  ); // false\n\n// Using the schema function with filter\nvar ducks   = animals.filter( Duck );                        // every Duck-like animal\nvar walking = animals.filter( schema({ walk : Function }) ); // every animal that can walk\n```\n\nIt is also possible to define self-referencing data structures:\n\n```javascript\nvar Tree = schema({ left : [ Number, Tree ], right : [ Number, Tree ] });\n\nconsole.log( Tree({ left : 3, right : 3 })                        ); // true\nconsole.log( Tree({ left : 3, right : { left: 5, right: 5 } })    ); // true\nconsole.log( Tree({ left : 3, right : { left: 5, right: 's' } })  ); // false\n```\n\nError reporting:\n\n```javascript\nDuck.errors({\n  swim: function() {},\n  quack: function() {},\n  age: 6,\n  color: 'green'\n});\n\n// {\n//   age: 'number = 6 is bigger than required maximum = 5',\n//   color: 'string = green is not reference to string = yellow AND\n//           string = green is not reference to string = brown'\n// }\n```\n\nUsage\n=====\n\nInclude js-schema in your project with `var schema = require('js-schema');` in node.js or with\n`\u003cscript src=\"js-schema.min.js\"\u003e\u003c/script\u003e` in the browser. AMD module loading is also supported.\n\nThe first parameter passed to the `schema` function describes the schema, and the return value\nis a new function called validator. Then the validator can be used to check any object against\nthe described schema as in the example above.\n\nThere are various patterns that can be used to describe a schema. For example,\n`schema({n : Number})` returns a validation function which returns true when called\nwith an object that has a number type property called `n`. This is a combination of the\nobject pattern and the instanceof pattern. Most of the patterns are pretty intuitive, so\nreading a schema description is quite easy even if you are not familiar with js-schema.\nMost patterns accept other patterns as parameters, so composition of patterns is very easy.\n\nExtensions are functions that return validator by themselves without using the `schema` function\nas wrapper. These extensions are usually tied to native object constructors, like `Array`,\n`Number`, or `String`, and can be used everywhere where a pattern is expected. Examples\ninclude `Array.of(X)`, `Number.min(X)`.\n\nFor serialization to JSON Schema use the `toJSON()` method of any schema (it returns an object)\nor call `JSON.stringify(x)` on the schema (to get a string). For deserialization use\n`schema.fromJSON(json)`. JSON Schema support is still incomplete, but it can reliably deserialize\nJSON Schemas generated by js-schema itself.\n\nPatterns\n========\n\n### Basic rules ###\n\nThere are 10 basic rules used for describing schemas:\n\n1. `Class` (where `Class` is a function, and has a function type property called `schema`)\n   matches `x` if `Class.schema(x) === true`.\n2. `Class` (where `Class` is a function) matches `x` if `x instanceof Class`.\n3. `/regexp/` matches `x` if `/regexp/.test(x) === true`.\n4. `[object]` matches `x` if `x` is deep equal to `object`\n5. `[pattern1, pattern2, ...]` matches `x` if _any_ of the given patterns match `x`.\n6. `{ 'a' : pattern1, 'b' : pattern2, ... }` matches `x` if `pattern1` matches `x.a`,\n   `pattern2` matches `x.b`, etc. For details see the object pattern subsection.\n7. `primitive` (where `primitive` is boolean, number, or string) matches `x` if `primitive === x`.\n8. `null` matches `x` if `x` _is_ `null` or `undefined`.\n9. `undefined` matches anything.\n10. `schema.self` references the schema returned by the last use of the `schema` function.\n    For details see the self-referencing subsection.\n\nThe order is important. When calling `schema(pattern)`, the rules are examined one by one,\nstarting with the first. If there's a match, js-schema first resolves the sub-patterns, and then\ngenerates the appropriate validator function and returns it.\n\n### Example ###\n\nThe following example contains patterns for all of the rules. The comments\ndenote the number of the rules used and the nesting level of the subpatterns (indentation).\n\n```javascript\nvar Color = function() {}, x = { /* ... */ };\n\nvar validate = schema({                    // (6) 'object' pattern\n  a : [ Color, 'red', 'blue', [[0,0,0]] ], //     (5) 'or' pattern\n                                           //         (2) 'instanceof' pattern\n                                           //         (7) 'primitive' pattern\n                                           //         (4) 'deep equality' pattern\n  b : Number,                              //     (1) 'class schema' pattern\n  c : /The meaning of life is \\d+/,        //     (3) 'regexp' pattern\n  d : undefined,                           //     (9) 'anything' pattern\n  e : [null, schema.self]                  //     (5) 'or' pattern\n                                           //         (8) 'nothing' pattern\n                                           //         (10) 'self' pattern\n});\n\nconsole.log( validate(x) );\n```\n\n`validate(x)` returns true if all of these are true:\n* `x.a` is either 'red', 'blue', an instance of the Color class,\n  or an array that is exactly like `[0,0,0]`\n* `x.b` conforms to Number.schema (it return true if `x.b instanceof Number`)\n* `x.c` is a string that matches the /The meaning of life is \\d+/ regexp\n* `x` doesn't have a property called `e`, or it does but it is `null` or `undefined`,\n  or it is an object that matches this schema\n\n### The object pattern ###\n\nThe object pattern is more complex than the others. Using the object pattern it is possible to\ndefine optional properties, regexp properties, etc. This extra information can be encoded in\nthe property names.\n\nThe property names in an object pattern are always regular expressions, and the given schema\napplies to instance properties whose name match this regexp. The number of expected matches can\nalso be specified with `?`, `+` or `*` as the first character of the property name. `?` means\n0 or 1, `*` means 0 or more, and `+` means 1 or more. A single `*` as a property name\nmatches any instance property that is not matched by other regexps.\n\nAn example of using these:\n```javascript\nvar x = { /* ... */ };\n\nvar validate = schema({\n  'name'             : String,  // x.name must be string\n  'colou?r'          : String   // x must have a string type property called either\n                                // 'color' or 'colour' but not both\n  '?location'        : String,  // if x has a property called 'location' then it must be string\n  '*identifier-.*'   : Number,  // if the name of a property of x matches /identifier-.*/ then\n                                // it must be a number\n  '+serialnumber-.*' : Number,  // if the name of a property of x matches /serialnumber-.*/ then\n                                // it must be a number and there should be at least one such property\n  '*'                : Boolean  // any other property that doesn't match any of these rules\n                                // must be Boolean\n});\n\nassert( validate(x) === true );\n```\n\n### Self-referencing ###\n\nThe easiest way to do self-referencing is using `schema.self`. However, to support a more\nintuitive notation (as seen in the Tree example above) there is an other way to reference\nthe schema that is being described. When executing this:\n\n```javascript\nvar Tree = schema({ left : [ Number, Tree ], right : [ Number, Tree ] });\n```\n\njs-schema sees in fact `{ left : [ Number, undefined ], right : [ Number, undefined ] }` as first\nparameter, since the value of the `Tree` variable is undefined when the schema function is\ncalled. Consider the meaning of `[ Number, undefined ]` according to the rules described above:\n'this property must be either Number, or anything else'. It doesn't make much sense to include\n'anything else' in an 'or' relation. If js-schema sees `undefined` in an or relation, it assumes\nthat this is in fact a self-reference.\n\nUse this feature carefully, because it may easily lead to bugs. Only use it when the return value\nof the schema function is assigned to a newly defined variable.\n\nExtensions\n==========\n\n### Numbers ###\n\nThere are five functions that can be used for describing number ranges: `min`, `max`, `below`,\n`above` and `step`. All of these are chainable, so for example `Number.min(a).below(b)` matches `x`\nif `a \u003c= x \u0026\u0026 x \u003c b`. The `Number.step(a)` matches `x` if `x` is a divisible by `a`.\n\n### Strings ###\n\nThe `String.of` method has three signatures:\n- `String.of(charset)` matches `x` if it is a string and contains characters that are included in `charset`\n- `String.of(length, charset)` additionally checks the length of the instance and returns true only if it equals to `length`.\n- `String.of(minLength, maxLength, charset)` is similar, but checks if the length is in the given interval.\n\n`charset` must be given in a format that can be directly inserted in a regular expression when\nwrapped by `[]`. For example, `'abc'` means a character set containing the first 3 lowercase letters\nof the english alphabet, while `'a-zA-C'` means a character set of all english lowercase letters,\nand the first 3 uppercase letters. If `charset` is `undefined` or `null` then there's no restriction on\nthe character set.\n\n### Arrays ###\n\nThe `Array.like(array)` matches `x` if `x instanceof Array` and it deep equals `array`.\n\nThe `Array.of` method has three signatures:\n- `Array.of(pattern)` matches `x` if `x instanceof Array` and `pattern` matches every element of `x`.\n- `Array.of(length, pattern)` additionally checks the length of the instance and returns true only if it equals to `length`.\n- `Array.of(minLength, maxLength, pattern)` is similar, but checks if the length is in the given interval.\n\n### Objects ###\n\n`Object.reference(object)` matches `x` if `x === object`.\n\n`Object.like(object)` matches `x` if `x` deep equals `object`.\n\n### Functions ###\n\n`Function.reference(func)` matches `x` if `x === func`.\n\nFuture plans\n============\n\nBetter JSON Schema support. js-schema should be able to parse any valid JSON schema and generate\nJSON Schema for most of the patterns (this is not possible in general, because of patterns that hold\nexternal references like the 'instanceof' pattern).\n\nContributing\n============\n\nFeel free to open an issue or send a pull request if you would like to help improving js-schema or find a bug.\n\nPeople who made significant contributions so far:\n\n * [Alan James](https://github.com/alanjames1987)\n * [Kuba Wyrobek](https://github.com/parhelium)\n * [Mikael Berg](https://github.com/mikberg)\n * [Alex Ivanov](https://github.com/alex-ivanov)\n\nInstallation\n============\n\nUsing [npm](http://npmjs.org):\n\n    npm install js-schema\n\nUsing [bower](http://bower.io):\n\n    bower install js-schema\n\nBuild\n=====\n\nTo build the browser version you will need node.js and the development dependencies that can be\ninstalled with npm (type `npm install ./` in the project directory). `build.sh`\nassembles a debug version using browserify and then minifies it using uglify.\n\nLicense\n=======\n\nThe MIT License\n\nCopyright (C) 2012 Gábor Molnár \u003cgabor@molnar.es\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmolnarg%2Fjs-schema","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmolnarg%2Fjs-schema","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmolnarg%2Fjs-schema/lists"}