Validate objects against predefined rules (node.js).
A tiny rules framework that can be used to validate any value, either by you creating a rules/schema object or applying validations to a single value. In both cases a fluent interface is used.
You create an object to declare the rules/invariants you want to apply (something akin to a schema). A fluent interface makes it easy to specify the invariants for each property:
var nameRules =first : mustBepopulatedstring minLength: 5 maxLength: 20 1second : mustBepopulatedstring minLength: 5 maxLength: 20var personRules =name: nameRulesweight: mustBepopulatednumericmin : 0 max: 130thispopulateddate before: nowsubtract"years" 1 ;2
As shown you can access this fluent interface using two approaches:
The function based approach is designed primarily for use with CoffeeScript:
# This schema is not showing how to validate a real address, it just shows a few validatorsaddressRules =streetOne: mustBepopulated: -> @populatedstring minLength: 10maxLength : 50: -> @populatedstring minLength : 10maxLength: 50: -> @populated: -> @populatedmatchFor/.../
The same validators are available for use validating individual values:
You trigger validation using:
result = rules.apply(person, personRules)
The returned object has the per-property details of any validation failures, e.g.:
name:first:message: 'The value must be populated.'type: 'not_populated'value: ''second:message: 'The value must be populated.'type: 'not_populated'value: undefinedweight:message: 'The value must be populated.'type: 'not_populated'value: undefined
Note in this case both the first name (e.g. person.name.first) and second name (person.name.second) needed to be populated, along with the weight.
The framework comes with several validators, to understand them further you may want to run the examples.
populated- Checks the value is not
"", or an empty array.
numeric- Optionally you can also pass in object with
matchFor- You can pass in an object with
flags, alternatively you can pass in the
RegExpobject to use.
date- Optionally you can specify that the date must be
afterspecified dates. To make this easier you use
now.subtractto specify the dates to use for
string- Optionally you can pass in
The project comes with examples in the examples directory.
mocha -R spec spec/testFixture spec/ --recursive