npm.io
1.0.1 • Published 5 years ago

koa-param-validate

Licence
ISC
Version
1.0.1
Deps
0
Size
6 kB
Vulns
0
Weekly
0

koa-param-validate

a validator for koa

Install

$ npm install koa-param-validate --save

Usage

Example
// app.js
const Koa = require("koa")
const koaParamValidate = require("koa-param-validate")

const app = new Koa()

koaParamValidate(app)

app.listen(3000, () => {
  console.log("server is running...")
})
// controller/auth.js
module.exports = (app) => ({
  async login() {
    const { ctx } = app

    try {
      ctx.validate({
        username: "string",
        password: "string",
      });
    } catch (error) {
      console.log(error);
    }

    ctx.body = {
      code: 200,
      msg: "success",
    }
  }
})

Api

ctx.validate({
  username: "string",
  age: "number",
})
// add password rule
app.validator.addRule("password", (rule, value) => {
  if (value.toString().length < 6) {
    return "the length cannot be less than 6 characters"
  }
})

Keywords