• Stars
    star
    159
  • Rank 235,916 (Top 5 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JSON Schema validation library for Javascript / Node / Express.

Schema Validation for JavaScript

Barebones schema validation library for things such as database schemas, api data schemas, etc.

Install

$ npm install schema-validator

For browsers, download and include the script validator.js just as you would jquery or another script.

Implementations

  • Required (built-in)
  • Default (built-in) - is done during required check, and is placed even if required exists.
    • This functionality is subject to change (placed even if required part). Let me know in issues.
  • Type - uses Object.prototype.toString.call so make sure you use String, Number, Boolean... etc.
  • Length - By itself it must be this long, otherwise as an object supports the following:
    • Min
    • Max
  • Test (Regular expression tests)
    • Supports an array of RegExps as well.

Usage

You create a JSON Schema, where username is a field, and each key:value inside of it is an implementation in validator.

var schema = {
  username: {
    type: String,
    required: true,
    length: {
      min: 3,
      max: 36
    },
    test: /^[a-z0-9]+$/gi
  }
};

Setup a new Validator against your schema:

var validator = new Validator(schema);

Note there is also debugging support you can enable by adding the following line:

validator.debug = true;

Now we validate against some given information:

var check = validator.check({
  username: "Niji%kokun"
});

console.log(check);
Nesting

Nesting is supported, it's currently in a testing phase, as seen in the test file:

  belt: {
    type: Object,
    required: true,

    team: {
      type: Array,
      required: true,
      length: {
        min: 1,
        max: 6
      }
    },

    inventory: {
      type: Array,
      default: [],
      length: {
        max: 255
      }
    }
  }
Express Middleware Style:

Schema data will be put on the request object, req.validated, as an Object containing field : data information.

app.get('api/user/add', [ new Validator(schema.user, true) ], function (req, res) {
  res.send(200, req.validated);
});

or

app.get('api/user/add', [ (new Validator(schema.user)).middleware() ], function (req, res) {
  res.send(200, req.validated);
});

Creating an extension

Implementing a feature into Validator is easy, you set the field and a callback.

The callback supports a single argument options which contains valuable information.

  • field - The field implementation that is being checked.
  • key - The schema field being checked.
  • data - The data passed from an external source.
  • value - The field implementation data value.
  • error - Sugar method for this.error which was previously used.
    • type - optional argument, it's the error field for the message given. Default is field.
    • message - Error message.
Validator.implement("field", function (options) {
  if (options.data) {
    options.error("Data exists, this is wrong... or right! I don't know!");
  }

  // If you couldn't tell this gives an error back to the validator
  options.error("No check has been done against this key!");

  // and you can set custom field name for the error message object
  options.error("error-field", "This field hasn't been checked yet!");
});

After your implementation has been ran, the validator will check for errors, if found it will exit out and return the errors. You can pass along multiple errors per run, for an example check the test implementation.

Todo

  • Make extensibility easier.
  • Move over to github repository.
  • Make implementations use an object as an argument rather than multiple arguments.
  • Implement nesting feature. Might be useful, I personally can't see one... let me know in issues if you can.
  • Implement check for Array values.
  • Implement support for wildcard, it could be useful to work with all fields that aren't plugins under one object.
  • Break up implementations into their own folder and make a compiler.
    • Browserify?

Changelog

Version 3.3.0

  • Clean code
  • Optimize middleware to rely on .check
  • Fix issue #6
  • Fix issue #4
    • Requires .middleware to be invoked when used instead of referenced.

Version 3.2.2

  • Implemented nesting abilities.
    • I think the current implementation is fairly quick, but I feel there is a faster way using references.

Version 3.2.1

  • Implemented default field.
    • Supported even on required fields, may be subject to change. Let me know in issues how you feel.

Version 3.2.0

  • Fix test, now can be run with node
  • Fix length for Numbers with extended support for Arrays
  • Fix loop issue where only one value was returned
  • Implement support for natives no longer need to use strings for types
    • Function, String... are supported, check password.type in test for more information.
  • Implement debug feature for showing value of fields along with error messages.
  • Simplified roundup.

Version 3.1.0

  • Extend comments
  • Implement module exporting for various platforms.

Version 3.0.0

  • Remove console logging
  • Implement plugin system - .implement method

Version 2.0.0

  • Fix slight bugs in matching validation check
  • Make errors Object based for quick key referencing

Version 1.0.0

  • Initial Release.

More Repositories

1

generate-schema

🧞 Convert JSON Objects to MySQL, JSON Schema, Mongoose, Google BigQuery, Swagger, and more.
JavaScript
1,026
star
2

minami

πŸ’… Clean and minimal JSDoc 3 Template / Theme
JavaScript
573
star
3

file-size

πŸ“‚ Lightweight filesize to human-readable / proportions w/o dependencies for node.js & browsers.
JavaScript
233
star
4

the-zen-approach

JavaScript Styleguide, can be applied to other things as well.
168
star
5

WinScreeny

Windows Screenfetch - Remember that linux only one? Not anymore.
Shell
86
star
6

Geometry.js

Javascript Geometry Class for Games / Etc
JavaScript
82
star
7

clarity

Clarity theme for Gitbook designed for The Zen Approach
CSS
74
star
8

http-responses

Node.js Middleware for standardizing the way you send HTTP response statuses.
JavaScript
46
star
9

Hasher

Javascript URL Hash Routing Made Simple.
JavaScript
45
star
10

fluf

A Fast, Minimalistic, Micro Routing / Web Application Framework for PHP5; Modeled after Sinatra.
PHP
40
star
11

breeze

Javascript async flow control manager
JavaScript
39
star
12

Diacritics.js

Diacritic javascript module for cleaning or stripping a string of accents and replacing them with an equivalent.
JavaScript
31
star
13

query-js

Query parser using native javascript, with caching on both the decoder and parser.
JavaScript
28
star
14

stripe-mock-webhooks

Node.js module for testing Stripe Webhooks, no internet required
JavaScript
25
star
15

Templator

JS Template Manager and Controller. Allows for external files, elements, and raw data, and supports over 9 template languages.
JavaScript
25
star
16

iConomy

Economy Java Plugin for hey0's Mod
Java
21
star
17

mithril-router

Django style router for Mithril.js
JavaScript
19
star
18

ukiyo

πŸƒβ€β™‚οΈ Barebones Single Page Application Development Server in Nodejs
JavaScript
19
star
19

mithril-validator

Easily validate Mithril.js forms, models, and objects.
JavaScript
19
star
20

diffr

CLI diff tool for files, text, and JSON with human readable output.
JavaScript
17
star
21

General

General plugin for Bukkit
Java
16
star
22

sugarcube-starter

Easy to use starter kit for creating stories with Tweego, Twine and SugarCube.
JavaScript
15
star
23

Prevu

SublimeText -> Browser Preview
Python
15
star
24

stripe-mock-data

Node.js Stripe webhook & object data for mocking / testing purposes.
JavaScript
14
star
25

careful

Validate git branches according to git-flow before you push / commit code.
JavaScript
13
star
26

fantasy-ui

Clean, flat dark ui for Atom.
CSS
12
star
27

array-to-table

Convert an array of objects to a simple markdown table.
JavaScript
12
star
28

NinkoBB

Small, Flexible, and Powerful Open source Forum Script.
PHP
12
star
29

drink

Terminal Application Helper. Keep sessions alive, process input data, or output data. Go ahead, take a sip.
CoffeeScript
12
star
30

Permissions

Java
11
star
31

dotfiles

πŸ“ Make Dotfiles Great Again πŸ“
Vim Script
10
star
32

ractive.sortable.js

Ractive sortable event definition
JavaScript
9
star
33

ractive.drag.drop.js

Native HTML5 Drag N' Drop ractive event definition.
JavaScript
9
star
34

telepath

Dark theme for CIRC (Chrome IRC)
CSS
8
star
35

.todo

@todo a human-readable .todo language & syntax. Watch/Fork this project!
JavaScript
8
star
36

mithril-tour-component

Tour Guide Component for Mithril.js
JavaScript
7
star
37

Markdown

Markdown for PHP
PHP
7
star
38

n0p3

You probably shouldn't use this Node.js module ever
JavaScript
7
star
39

NASA

Thin #Javascript wrappers for #HTML5 #API.
JavaScript
7
star
40

dollars-to-cents

Convert USD Dollars (formatted string, non-formatted, numerical value) to USD Cents (numerical).
JavaScript
7
star
41

WarpGates

WarpGates for Bukkit - Portal through time and blackholes!
Java
7
star
42

iConomy3

Please, if you fork iConomy only do so if you are really fixing or adding something useful!
Java
7
star
43

Estro

Extended String Object for JavaScript
JavaScript
6
star
44

butisitwebscale.com

Just pure science and mathematics to determine whether technologies are webscale
CSS
6
star
45

nasa-keypath

New Age Keypath Traversal Technology.
JavaScript
6
star
46

todo-tmbundle

@todo Textmate Syntax Highlighting, Works in Sublime Text / E as well.
5
star
47

nuuid

Not (another) unique universal identifier... But, it is. Faster and less prone to collisions than uuid as the scheme is ever changing, yet forever stable.
JavaScript
5
star
48

java.php

Java ported to PHP OOP
PHP
5
star
49

mithril-requests

Add sugar HTTP methods to Mithril.js
JavaScript
5
star
50

raygun-winston

Raygun transport for NodeJS Winston logging library
JavaScript
5
star
51

bacon.css

Bacon CSS. Delicious Syntax. Let's Get Sizzlin' - Check the link below for an example!
JavaScript
4
star
52

MiniJS

Better looking MicroJS
4
star
53

SimpleShop

Java
4
star
54

utils.js

Javascript Utilities, Snippets, and Knowledge Base
JavaScript
4
star
55

MiniDB

Tiny FlatFile Database
Java
4
star
56

mithril-component

React style components for mithril, easy and simple to use.
JavaScript
4
star
57

Cleaner

Java
3
star
58

electron-vue-starter

🌱 Base starter for Electron 6 / Vue 2.6 with Vue Router, Vuex, and more!
JavaScript
3
star
59

Tipper

Java
3
star
60

juttles

Commonly used / made Javascript / CoffeeScript utilities.
3
star
61

Transparent-Grid

A responsive grid system that works for fixed and fluid layouts written in stylus.
3
star
62

iChat

Java
3
star
63

havoc

Havoc Game Framework (originally god.js)
JavaScript
2
star
64

docker-ubuntu-image

Docker Base Image for Rapid Developer Environments
Shell
2
star
65

CommandCost

Example iConomy Addon Plugin
Java
2
star
66

napkin-bar

Design Patterns & Articles to help build a scalable Javascript application.
2
star
67

kong-plugin-prometheus

Kong plugin that enables an endpoint for Prometheus to access and obtain Kong metrics
Lua
2
star
68

lua-find

Javascript implementation of Lua's String.find functionality
JavaScript
2
star
69

mChat

mChat - Chat Formatting Plugin
Java
1
star
70

NiiGen

Python Psuedo-Random Password/Key Gen
Python
1
star
71

electron-react-starter

🌱 Base starter for Electron 7.x with React 16.x
JavaScript
1
star
72

ls_editsuite

A "web interface" to do stuff with LocalShops shops... currently supports V3
PHP
1
star
73

Reserves

Reserve list for Bukkit
1
star
74

Glonick

Java
1
star
75

Heirarchy

Permissions Configuration Language - HARC
Java
1
star
76

Bukget-Plugin

Bukkit bukget Plugin.
Java
1
star
77

nodoc

Easy, Simplified, Documentation Syntax Block Proposal for the JavaScript Language
1
star
78

SignTrader

Java
1
star
79

chariot

Chariot is a aggregated package manager, currently supports npm, and bower.
Shell
1
star
80

iAuction

iConomy Auctions
1
star