silfverorg / duns.js

Javascript schema validator
5 stars 2 forks source link

Duns.js

Duns - schema validator for javascript.

npm version Build Status

Methods

Currently supports the following validators,

To use, create a schema and validate.

var Schema = Duns.object().keys({
    pirate : Duns.object().keys({
        ninja  : Duns.string().minlen(2),
        parrot : Duns.number()
            .max(140).min(90).greater(90)
            .positive()
        })
})

var data = { pirate : { ninja : 'test', parrot : 100 } };

// Then you can validate the schema like this.
Duns.validate(data, Schema) // Validates as true.

// Or like this.
Schema.init(data).validate() // Valides as true.

// Or even like this.
var schema = Duns.number();
schema.validate(100); // Validates as true.

// To get failure msg
var schema = Duns.any().invalid(5);
if (!schema.validate(5)) {
  console.log(schema.failure);
}

Duns can also assist in formatting values given a schema.

    var Schema = Duns.object().keys({
      age: Duns.number().returns(function(age) {
        returns age * 2;
      }),

      name : Duns.string().returns(function(name) {
        returns name + '!';
      }),
    });

    Schema.init({ age:20, name: 'test' }).format();
    //Returns { age:40, name: 'test!' }

Duns

Duns.any

Validation methods

var schema = Duns.any().extend({
  isBetween : function(val, min, max) {
    return val < max && val > min;
  }
});

schema.isBetween(10, 20);
schema.validate(15) // returns true.

Formatting methods

Duns.bool

Must either be true or false. Extends Duns.any.

Validation methods

Duns.number

Must be number. Extends Duns.any.

Duns.string

Must be string. Extends Duns.any.

Duns.array

Must be array. Extends Duns.any.

Duns.object

Must be object. Extends Duns.any.

Duns.date

Must be valid date. Extends Duns.any. Uses moment.js internally.