Blog

Introducing node-validation

May 3, 2013

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.

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.

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);

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

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be