1.0.0 • Published 7 years ago

vtypes-shape v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

vtypes-shape

"shape" validation for validate.js

npm package vtypes

About

The shape validator attempts to ensure that the object validates against the sub-rule.

It is meant to provide nested validations instead of using deep nested attributes as the keys.

i.e.

// instead of
const constraints = {
  'deep.attr': {presence: true}
}

// use natural nesting
const constraints = {
  'deep': {
    'shape': {
      'values': {
        'attr': {presence: true}
      }
    }
  }
}

Installation

Using npm:

$ npm i --save vtypes-shape
const validate = require('validate.js');
const shape = require('vtypes-shape');

// you can then proceed to register the required validators.
validate.validators.shape = shape;

Usage

validate({}, {attr: {shape: true}});
// => undefined

validate({attr: {}, {attr: {shape: false}});
// => undefined

validate({attr: 'foo'}, {attr: {shape: true}});
// => {attr: {_message: 'Attr is not of type object'}}
const value = {
  attr: {
    b: 't2'
  }
};

const constraints = {
  attr: {
    shape: {
      values: {
        a: {
          presence: true,
        },
        b: {
          length: {is: 3}
        }
      }
    }
  }
};

validate(value, constraints);
// {
//   attr: {
//      a: [
//        'A can\'t be blank'
//      ],
//      b: [
//        'B is the wrong length (should be 3 characters)'
//      ]
//      _message: '^One or more object values for value is not valid',
//   }
// };

For more examples, check out the test files in this package's source folder.

Available Options

nametypedefaultdescription
formatterfunction(v) => vAllows processing of errors before it returns
messagestring^One or more object values for %{key} is not validError message
messageKeystring_messagekey in return object for the summary message
notObjectstring%{key} is not of type objectError when value is not an object

License

vtypes-shape is MIT licensed