• Stars
    star
    592
  • Rank 72,695 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 12 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

A cross-browser / node.js validator powered by JSON Schema

revalidator Build Status

A cross-browser / node.js validator with JSONSchema compatibility as the primary goal.

Example

The core of revalidator is simple and succinct: revalidator.validate(obj, schema):

  var revalidator = require('revalidator');

  console.dir(revalidator.validate(someObject, {
    properties: {
      url: {
        description: 'the url the object should be stored at',
        type: 'string',
        pattern: '^/[^#%&*{}\\:<>?\/+]+$',
        required: true
      },
      challenge: {
        description: 'a means of protecting data (insufficient for production, used as example)',
        type: 'string',
        minLength: 5
      },
      body: {
        description: 'what to store at the url',
        type: 'any',
        default: null
      }
    }
  }));

This will return with a value indicating if the obj conforms to the schema. If it does not, a descriptive object will be returned containing the errors encountered with validation.

  {
    valid: true // or false
    errors: [/* Array of errors if valid is false */]
  }

In the browser, the validation function is exposed on window.validate by simply including revalidator.js.

Installation

Installing npm (node package manager)

  $ curl http://npmjs.org/install.sh | sh

Installing revalidator

  $ [sudo] npm install revalidator

Usage

revalidator takes json-schema as input to validate objects.

revalidator.validate (obj, schema, options)

This will return with a value indicating if the obj conforms to the schema. If it does not, a descriptive object will be returned containing the errors encountered with validation.

{
  valid: true // or false
  errors: [/* Array of errors if valid is false */]
}

Available Options

  • validateFormats: Enforce format constraints (default true)
  • validateFormatsStrict: When validateFormats is true treat unrecognized formats as validation errors (default false)
  • validateFormatExtensions: When validateFormats is true also validate formats defined in validate.formatExtensions (default true)
  • additionalProperties: When additionalProperties is true allow additional unvisited properties on the object. (default true)
  • cast: Enforce casting of some types (for integers/numbers are only supported) when it's possible, e.g. "42" => 42, but "forty2" => "forty2" for the integer type.

Schema

For a property an value is that which is given as input for validation where as an expected value is the value of the below fields

required

If true, the value should not be undefined

{ required: true }

allowEmpty

If false, the value must not be an empty string

{ allowEmpty: false }

type

The type of value should be equal to the expected value

{ type: 'string' }
{ type: 'number' }
{ type: 'integer' }
{ type: 'array' }
{ type: 'boolean' }
{ type: 'object' }
{ type: 'null' }
{ type: 'any' }
{ type: ['boolean', 'string'] }

pattern

The expected value regex needs to be satisfied by the value

{ pattern: /^[a-z]+$/ }

maxLength

The length of value must be greater than or equal to expected value

{ maxLength: 8 }

minLength

The length of value must be lesser than or equal to expected value

{ minLength: 8 }

minimum

Value must be greater than or equal to the expected value

{ minimum: 10 }

maximum

Value must be lesser than or equal to the expected value

{ maximum: 10 }

allowEmpty

Value may not be empty

{ allowEmpty: false }

exclusiveMinimum

Value must be greater than expected value

{ exclusiveMinimum: 9 }

exclusiveMaximum

Value must be lesser than expected value

{ exclusiveMaximum: 11 }

divisibleBy

Value must be divisible by expected value

{ divisibleBy: 5 }
{ divisibleBy: 0.5 }

minItems

Value must contain more than expected number of items

{ minItems: 2 }

maxItems

Value must contain fewer than expected number of items

{ maxItems: 5 }

uniqueItems

Value must hold a unique set of values

{ uniqueItems: true }

enum

Value must be present in the array of expected values

{ enum: ['month', 'year'] }

format

Value must be a valid format

{ format: 'url' }
{ format: 'email' }
{ format: 'ip-address' }
{ format: 'ipv6' }
{ format: 'date-time' }
{ format: 'date' }
{ format: 'time' }
{ format: 'color' }
{ format: 'host-name' }
{ format: 'utc-millisec' }
{ format: 'regex' }

conform

Value must conform to constraint denoted by expected value

{ conform: function (v) {
    if (v%3==1) return true;
    return false;
  }
}

dependencies

Value is valid only if the dependent value is valid

{
  town: { required: true, dependencies: 'country' },
  country: { maxLength: 3, required: true }
}

Nested Schema

We also allow nested schema

{
  properties: {
    title: {
      type: 'string',
      maxLength: 140,
      required: true
    },
    author: {
      type: 'object',
      required: true,
      properties: {
        name: {
          type: 'string',
          required: true
        },
        email: {
          type: 'string',
          format: 'email'
        }
      }
    }
  }
}

Custom Messages

We also allow custom messages for different constraints

{
  type: 'string',
  format: 'url'
  messages: {
    type: 'Not a string type',
    format: 'Expected format is a url'
  }
{
  conform: function () { ... },
  message: 'This can be used as a global message'
}

Tests

All tests are written with vows and should be run with npm:

  $ npm test

Author: Charlie Robbins, Alexis Sellier

Contributors: Fedor Indutny, Bradley Meck, Laurie Harper, Martijn Swaagman

License: Apache 2.0

More Repositories

1

director

a tiny and isomorphic URL router for JavaScript
JavaScript
5,622
star
2

prompt

a beautiful command-line prompt for node.js
JavaScript
1,860
star
3

cradle

a high-level CouchDB client for Node.js
JavaScript
1,377
star
4

flatiron

framework components for node.js and the browser
JavaScript
1,340
star
5

plates

Light-weight, logic-less, DSL-free, templates for all javascript environments!
JavaScript
830
star
6

blacksmith

A generic static site generator built using flatiron, plates, and marked.
JavaScript
556
star
7

resourceful

an isomorphic Resource engine for JavaScript
JavaScript
352
star
8

restful

reflect RESTful Director routers from Resourceful resources
JavaScript
236
star
9

cliff

Your CLI formatting friend
JavaScript
194
star
10

union

A hybrid buffered / streaming middleware kernel backwards compatible with connect.
JavaScript
136
star
11

utile

A drop-in replacement for `util` with some additional advantageous functions
JavaScript
95
star
12

socketful

reflect socket.io event maps from Resourceful resources
JavaScript
44
star
13

director-reflector

reflect isomorphic HTTP client API wrappers from Director routers
JavaScript
21
star
14

viewful

a tiny and isomorphic consolidated view engine for JavaScript
JavaScript
19
star
15

cli-config

Encapsulated commands for managing configuration in flatiron CLI apps
JavaScript
17
star
16

www

The public web presence for flatiron
CSS
12
star
17

director-explorer

HTML / Text view of `Director.router` instances
JavaScript
12
star
18

commandful

reflect Command Line Interfaces from Resourceful resources
JavaScript
12
star
19

http-users

Encapsulated routes and resources for managing users in flatiron HTTP apps
JavaScript
11
star
20

cli-users

Encapsulated commands for managing users in flatiron CLI apps
JavaScript
10
star
21

formful

reflect HTML forms from Resourceful resources
JavaScript
10
star
22

blacksmith-sites

a collection of pre-built site generators for the blacksmith engine
JavaScript
7
star
23

hello-world-flatiron-api

Sample Flatironjs Application - Hello World API
JavaScript
7
star
24

cortex.js

A front-end framework
JavaScript
4
star
25

broadway-godot

Plugin that enables godot on the broadway instance through magic
JavaScript
1
star