1.1.2 • Published 4 years ago

koa-better-validator v1.1.2

Weekly downloads
1
License
ISC
Repository
-
Last release
4 years ago

Installation


The library was inspired by the validator.js.

$ npm i koa-better-validator -S

or

$ yarn add koa-better-validator -S

Usage


const Koa = require('koa')
const { koaValidator, KoaValidatorException } = require('koa-better-validator')
const app = new Koa()

// catch exception
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (e) {
    if(e instanceof KoaValidatorException) {
      ctx.body = {
        errMsg: e.errMsg || 'This is koa-better-validator catch errors'
      } 
    }
  } 
})

// customize you validator
app.use(koaValidator({
  customValidators: {
    isString (param) {
      return Object.prototype.toString.call(param) === '[object String]' ? param : false;
    }
    // other customValidators
}
}))

app.use(async (ctx, next) => {
  // The method verify will automatically identify from body、params、query、header
  // ctx.query, ctx.params, ctx.request.body(if you have used a library like koa-bodyparser), headers
  ctx.verify('name', 'the name length should be between 6 and 10 ').isLength({min: 6, max: 10})
  const { name } = await ctx.valid()
  console.log(name)
  await next()
})

app.listen(3000)
1.1.2

4 years ago

1.1.0

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago