node-validation-pod
All object validation libraries come bundled with their own assertion / sanitization primitives. Which is kind of dumb. There is a lot of great libraries such as chai.js or validator.js which could and should be used instead.
node-validation-pod is just an empty shell for running synchronous / asynchronous validation on objects. It doesn't come with any functionality for validating data. Only the validation logic. This way, you can plug-in any validation library you want.
The validation logic
Implements 3 steps :
- before : prepare your data for validation. If some fields validity depend on each other, you can check it here. If a validation error occurs, go directly to
after
step. - attributes validators : for each attribute in your object, run the corresponding validator. Gathers all errors in one object.
- after : check for unknown attributes. Add errors to the errors found in previous step.
Example 1 : object validation using validator.js
Here is a simple example on how to use validator.js to validate the data submitted in a user sign-up form.
var chai = vpod = userRegisterValidator = { if !validator return 'Invalid email' } { if ! return 'Password must be at least 8 characters!' // ... more validation rules } { if thispassword !== val return 'Passwords do not match' }
Example 2 : object validation using chai.js
First you need to create a subclass of Validator
:
var chai = vpod = inherits = inherits var { vpodValidator} // This hooks allows to catch errors that occur during any of the 3 steps// of the validation process.// Return a message if the error is a validation error and should be handled,// return nothing or `false` if the error has not been handled and should be thrown. ChaiValidatorprototype { if err instanceof chaiAssertionError return errmessage }
ChaiValidator
will allow us to validate data using chai assertions. Let's now create a validator for some boring Animal
object :
var fs = chai = expect = chaiexpect var animalValidator = // Example of synchronous validation { tobe } { tobe } { tobe } // Example of asynchronous validation (note the second argument is a `done` callback) // We want to validate that the folder where we put our animal's pictures exists. { fs }
Now let's validate some stuff :
// A valid animalvar aDog = species: 'dog' color: 'blue' age: 12 pictureFolder: '/tmp' animalValidator
// An unvalid animalvar anotherDog = species: 'dog' color: 1 age: 12 pictureFolder: '/waf waf' unknownAttribute: '???' animalValidator
API
class Validator(validators, beforeAfter)
Builds a new validator.
Validator.run(obj, [opts,] done)
Run the validation on obj
. Options can be :
prefix
: the prefix to add to the validation error keysvalidationErrors
: an object to populate with validation errors