0.0.1-6 • Published 7 years ago

koa-json-validator v0.0.1-6

Weekly downloads
2
License
ISC
Repository
github
Last release
7 years ago

koa-json-validator

Build Status npm version

A koa middleware for node-validator taking a json object inspired by express-validator.

It works by parsing a javascript object, which calls the original functions on node-validator. Meaning that it works with all of node-validator functions, it even passes options to the function.

Installation

npm install koa-json-validator --save

Usage

see also test-server.js

Full Example

// libraries
const koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();

// the validator middleware
const validator = require('koa-json-validator');

const port = process.env.PORT || 3000;
const app = koa();

app.use(bodyParser());
app.use(function*(next) {
    try {
        yield next;
    } catch (err) {
        this.status = err.status || 500;
        this.body = {
            error: err.message
        };
    }
});

// validation object, tip: load from json file :)
const registerValidation = {
    username: {
        isLength: {
            options: {
                min: 3,
                max: 9
            },
            errorMessage: 'Username must be between 3 and 9 characters'
        },
        isAlphanumeric: 'Username must be alphanumeric'
    },
    password: {
        isLength: {
            options: {
                min: 6
            },
            errorMessage: 'Password must be at least 6 characters'
        }
    }
};

// call the validator with a validation object
router.post('/register', validator(registerValidation), function*(next) {
    // do database checks

    this.body = {
        message: 'account created'
    };
});

app.use(router.routes());
app.listen(port);

License

Copyright (c) 2017, Joël Luijmes joelluijmes@gmail.com, ISC License

0.0.1-6

7 years ago

0.0.1-5

7 years ago

0.0.1-4

7 years ago

0.0.1-3

7 years ago

0.0.1-2

7 years ago

0.0.1-1

7 years ago

0.0.1-0

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago