Opinionated object validation function based on validator.js.
Install the package via yarn:
$ yarn add validator.js-validateor via npm:
$ npm install validator.js-validate --saveThis module exports a function that creates a validate function, for instance:
importcreateValidateFunctionfrom'validator.js-validate';constvalidate=createValidateFunction();The created validate function works just like validating an object, but replaces the last groups argument with an options object:
validate(data[Object], constraint[Object|Constraint], options[Object])
Returns given data masked with given constraint keys:
constdata={foo: 'bar',qux: 'qix'};constconstraint={foo: is.equalTo('bar')};console.log(validate(data,constraint));// { foo: 'bar' }console.log(validate(data,constraint,{mask: false}));// trueThrows a new error when validation fails. To enable this option you must pass an error class when creating the validate function as argument.
This error constructor should be prepared to receive violations as argument, for example:
importStandardErrorfrom'standard-error';importcreateValidateFunctionfrom'validator.js-validate';classValidationFailedErrorextendsStandardError{constructor(errors){super({ errors });}}constvalidate=createValidateFunction(ValidationFailedError);constdata={foo: 'bar'};constconstraint={foo: is.equalTo('biz')};try{validate(data,constraint);}catch(e){console.log(e);// ValidationFailedError {// errors: {// foo: [{// __class__: 'Violation',// assert: {// __class__: 'EqualTo',// ...// }// }]// }// }}}console.log(validate(data,constraint,{throws: false}));// {// foo: [{// __class__: 'Violation',// assert: {// __class__: 'EqualTo',// ...// }// }]// }Use this option to validate with validation groups:
constdata={foo: 'bar'};constconstraint={foo: [is('bar').EqualTo('bar'),is('biz').equalTo('biz')]};console.log(validate(data,constraint,{groups: 'biz'}));// {// foo: [{// __class__: 'Violation',// assert: {// __class__: 'EqualTo',// ...// }// }]// }console.log(validate(data,constraint,{groups: 'bar'}));// { foo: 'bar' }Use the test script to run the test suite:
$ yarn testTo test check coverage use the cover script:
$ yarn coverA full coverage report will be generated on the coverage folder.
$ yarn release [<version>| major | minor | patch]