koa2-validate

1.0.1 • Public • Published

koa2-validate

Build Status

A library that wrap validator.js package for koa.js to validate request parameters.

Installation and usage

The lib requires Koa.js to run.

$ npm install koa2-validate

No ES6

var validate = require('koa2-validate');

ES6

import validate from 'koa2-validate';
Usage example

const app = new Koa()
  .use(cors())
  .use(bodyParser())
  .use(validate()) //use before api routes!!
  .use(api.routes())
  

/**
Use as {param: 'required|methodNameWithoutPrefix'}
*/
api.get('/simple-list',
  async (ctx, next) => {
    ctx.validate({
      limit: 'required|numeric^{no_symbols: true}',
      page: 'required|numeric^{no_symbols: true}'
    })
})

The | symbol is a separator for rules.
Only required is build-in rule.
For other rules use method name from the Validate.js validators which STARTS with is prefix.
For example if you write '..|numeric' it will call isNumeric method from Validate.js lib.   For options you can use ^{}.
e.g. if you want to call isNumeric(myVar, {no_symbols: true}) then use ..|numeric^{no_symbols: true}

If the params not pass the rules it will respond with 422 status and error text ${key} should be ${rule}

ToDo

  • Make error texts more dynamic (maybe with option to pass from code)
  • Add support of methods without is prefix
  • Write tests

License

MIT

Package Sidebar

Install

npm i koa2-validate

Weekly Downloads

0

Version

1.0.1

License

ISC

Unpacked Size

4.63 kB

Total Files

3

Last publish

Collaborators

  • armenhajian