1.0.1 • Published 5 years ago

koa2-validate v1.0.1

Weekly downloads
3
License
ISC
Repository
github
Last release
5 years ago

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