3 May
2013

Introducing node-validation

Category:UncategorizedTag: :

Some time ago I was looking for a validation library/module for use in a small Express application that I was writing at the time. I couldn?t find anything that suited my taste so I decided to write one myself just for kicks. The goal was learning how to publish a module to npm and making a futile attempt to contribute something back to the vibrant Node.js community. node-validation is a minimal but slightly opinionated validation library for Node.js.

Installing node-validation can be done using the canonical package manager:

$ npm install node-validation

Validation rules must be defined in a custom validator by deriving from the base Validator.

var MyObjectValidator = function() {
    Validator.call(this);

    this.ruleFor('stringProperty').isNotEmpty();
    this.ruleFor('otherStringProperty').hasMaximumLength(10);

    this.ruleFor('numericStringProperty').isNumber()
        .withMessage('Oops, something is wrong ...');
    this.ruleFor('dateStringProperty')
        .matches(/^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/);

    this.ruleFor('numberProperty').isInteger();
    this.ruleFor('otherNumberProperty').isMaximum(5);

    this.ruleFor('exoticProperty').is(function(value) {
        return 3 === value.propertyA + value.propertyB;
    }).withMessage('Either propertyA or propertyB has an incorrect value.');
};

util.inherits(MyObjectValidator, Validator);

 

After creating a validator object, an object that needs to be validated (the subject) can be passed to the validate method. The validate method returns an array of validation errors specifying a message and the name of the violating property.

 

//
// Validation subject
//
var subject = {
    stringProperty: '',
    otherStringProperty: 'Some string value that is too long ...',

    numericStringProperty: '65.85 invalid',
    dateStringProperty: '2013-04-30 invalid',

    numberProperty: 'Some invalid number',
    otherNumberProperty: 48,

    exoticProperty: {
        propertyA: 1,
        propertyB: 1
    }
};

//
// Now it's time to validate
//
var validator = new MyObjectValidator();
var validationErrors = validator.validate(subject);

for(var i=0; i < validationErrors.length; i++) {
    console.log('Property name: ' + validationErrors[i].propertyName 
                + ', Message: ' + validationErrors[i].message);
}

 

There you go. Head over to the GitHub repository and give it a try. I?m definitely looking forward to hear your feedback.