GithubHelp home page GithubHelp logo

artzhookov / conform.js Goto Github PK

View Code? Open in Web Editor NEW

This project forked from okv/conform.js

0.0 2.0 0.0 73 KB

A schema validation and filtering framework for node.js

Home Page: https://github.com/okv/conform.js

License: Apache License 2.0

JavaScript 100.00%

conform.js's Introduction

conform

A schema validation and filtering framework for node.js
It's a fork of revalidator which extends him with ability to modify source object - apply default values, casts, filters to source objects (see castSource, applyDefaultValue at options, filter section) and other features such as additionalProperties option.

Currently conform with default options fully backward compatible with revalidator 0.1.5 (except browsers support which should be ok but don't well tested cause no convenient way to do that with vows testing framework which is currently used).

Example

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

  var conform = require('conform');
  
  console.dir(conform.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 */]
  }

Installation

Installing conform

  $ npm install conform

Usage

conform takes json-schema as input to validate objects.

conform.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)
  • 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 (default false)
  • castSource: Apply casting (see cast option above) to source object (default false)
  • additionalProperties: Default value for object additionalProperties attribute (default true)
  • applyDefaultValue: Apply value of default attribute to source object (default false)
  • validateDefaultValue: If true value of default attribute will be checked to conforms schema (default false)
  • exitOnFirstError: If true validation will be stopped after first error occurred, valid will be false and errors will contain single error (default false)
  • failOnFirstError: Like exitOnFirstError option but error will be thrown, property info of error will contain regular validation error information (default false)

Notice: all options (such as castSource, additionalProperties) as well as attributes (such as filter) which modifies source object do that directly and immediately. That means that if some property (e.g. property1) was modified but later, on other property (e.g. property2), validation or filtering fails source object will be with modified property1 despite on valid equals to false at result.

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 empty

{ required: true }

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: 'date' }
{ 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 }

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 then expected value number of items

{ minItems: 2 }

maxItems

Value must contains less then expected value 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 value

{ 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 (val, obj, prop) {
    // `obj` - current object at validation, `prop` - property name
    return val % 3 == 1;
  }
}

dependencies

Value is valid only if the dependent value is valid

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

filter

Apply filter on value

{
  filter: function (v) {
    return v.toLowerCase();
  }
}

filter attribute can be array of filters.
Filter applies only after successful validation of value.
Filter errors as validation errors sets valid to false and provides error description at errors array.
Complex types (array, object) can't be filtered directly, use filter for array items or object properties instead.

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 message 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

Clone repository from github, cd into cloned dir and install dev dependencies

  $ npm install

run tests

  $ npm test

conform.js author: Oleg Korobenko

revalidator authors: Charlie Robbins, Alexis Sellier

revalidator contributors: Fedor Indutny, Bradley Meck, Laurie Harper

License: Apache 2.0

conform.js's People

Contributors

okv avatar pksunkara avatar indexzero avatar ixti avatar artzhookov avatar indutny avatar mmalecki avatar marak avatar bmeck avatar nikmilson avatar roobingood avatar rkusa avatar southern avatar colinf avatar anton-makarov avatar coderarity avatar jfhbrook avatar liammclennan avatar slaskis avatar stefansedich avatar timoxley avatar vladimir-polyakov avatar fleg avatar ggoodman avatar yeikos avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.