Getting Started with Koa Validation

At the time of writing, koa-better-body was used as the choice of bodyparser and in my experience, is one of the more wholesome libraries for parsing the koa body. That being said, other popular body parsers should also do the trick. All Validator methods and properties are attached to the koa "this" context and can easily be applied everywhere.

Installation

npm install koa-validation --save

Initialization

var app = require('koa')();
var koaBody = require('koa-better-body');

var validate = require('koa-validation');

app.use(koaBody({
    'multipart': true
}));
app.use(validate());

To initialize, simply require the module and add it to the koa middleware stack. Please note that you would still need to require a library to parse the body.

Validate Query

app.use(function *(next){

    yield this.validateQueries({
        email: 'required|email',
        password: 'required|between:6,15'
    }, {
        email: "Invalid Email",
        password.between: "Invalid Password Length"
    }, {
        before: {
            email: "lowercase",
            password: "trim"
        }
    })

    if (this.validationErrors) {
        this.status = 422;
        this.body = this.validationErrors;
    } else {
        this.status = 200;
        this.body = { success: true }
    }
})

The above method is used to validate URL queries. All parameters attached to the URL can automatically be attached to koa validation by using this.validateQueries. The function takes three arguments.

ArgumentOptionalTypeDescription
RulestrueObjectA valid Rules Object. Check Concepts to know more
MessagestrueObjectA Valid Messages Object. Check Concepts to know more
FilterstrueObjectA Valid Filters Object. Check Concepts to know more

Validate Headers

app.use(function *(next){

    yield this.validateHeaders({
        x-token: 'required|match:123scd45',
        x-authorization: 'required|between:6,15'
    }, {
        x-token: "Invalid token",
    })

    if (this.validationErrors) {
        this.status = 422;
        this.body = this.validationErrors;
    } else {
        this.status = 200;
        this.body = { success: true }
    }
})

The above method is used to validate the HTTP headers. All headers can automatically be attached to koa validation by using this.validateHeaders. The function takes three arguments.

ArgumentOptionalTypeDescription
RulestrueObjectA valid Rules Object. Check Concepts to know more
MessagestrueObjectA Valid Messages Object. Check Concepts to know more
FilterstrueObjectA Valid Filters Object. Check Concepts to know more

Validate Body

app.use(function *(next){

    yield this.validateBody({
        foo: 'required',
        bar: 'required|equals:foo'
    }, {
        bar.equals: "You dont mess with the foo"
    }, {
        before: {
            foo: "hex:sha256"
        }
    })

    if (this.validationErrors) {
        this.status = 422;
        this.body = this.validationErrors;
    } else {
        this.status = 200;
        this.body = { success: true }
    }
})

The above method is used to validate the HTTP POST, PUT and DELETE Requests. The function takes three arguments.

ArgumentOptionalTypeDescription
RulestrueObjectA valid Rules Object. Check Concepts to know more
MessagestrueObjectA Valid Messages Object. Check Concepts to know more
FilterstrueObjectA Valid Filters Object. Check Concepts to know more

Validate Params

app.use(function *(next){

    yield this.validateParams({
        foo: 'required',
        bar: 'required|equals:foo'
    }, {
        bar.equals: "You dont mess with the foo"
    }, {
        foo: "hex:sha256"
    })

    if (this.validationErrors) {
        this.status = 422;
        this.body = this.validationErrors;
    } else {
        this.status = 200;
        this.body = { success: true }
    }
})

The above method is used to validate URL params. Params is a routing feature and hence an appropriate URL routing middleware needs to be used. The above param validation takes place on the foo.com/:username/:password parameters. So any placeholder parameters declared on the URL can be automatically handled.

ArgumentOptionalTypeDescription
RulestrueObjectA valid Rules Object. Check Concepts to know more
MessagestrueObjectA Valid Messages Object. Check Concepts to know more
FilterstrueObjectA Valid Filters Object. Check Concepts to know more

Validate Files

app.use(function *(next){

    yield this.validateFiles({
        cutePanda: 'required|name:cutie|image',
    },
    true
    {
        cutePanda.image: "Inappropriate format for cute panda"
    }, {
        cutePanda: {
            action: 'copy',
            args: '/usr/local/images/cutePanda.jpg',
            callback: function *(validator, file, destination){
                validator.addError('cutePanda', 'action', 'copy', 'Just checking if the callback action works!!')
            }
        }
    })

    if (this.validationErrors) {
        this.status = 422;
        this.body = this.validationErrors;
    } else {
        this.status = 200;
        this.body = { success: true }
    }
})

The above method is used to validate URL params. Params is a routing feature and hence an appropriate URL routing middleware needs to be used. The above param validation takes place on the foo.com/:username/:password parameters. So any placeholder parameters declared on the URL can be automatically handled.

ArgumentOptionalTypeDescription
RulestrueObjectA valid Rules Object. Check Concepts to know more
DeleteOnFailtrueBooleanIn case you wish to delete the temporary file if validation Fails
MessagestrueObjectA Valid Messages Object. Check Concepts to know more
FilterstrueObjectA Valid Filters Object. Check Concepts to know more