14.koa-表单验证

417 阅读1分钟

安装koa-bouncer

npm i koa-bouncer -S

使用

  • html
<form action="/user" method="post">
    用户名:<input type="text" name='username'> <br>
    <!-- <input type="email" name='email'> <br> -->
    密码:<input type="password" name='pwd1'> <br>
    确认密码:<input type="password" name='pwd2'> <br>
    <input type="submit" value="提交"><br>
</form>
  • 在入口js文件中使用中间件
// 注册koa-bouncer,为了给ctx提供一些帮助方法
const bouncer = require('koa-bouncer');
app.use(bouncer.middleware());
  • user.js
//表单验证
const bouncer = require('koa-bouncer');
router.post('/', async (ctx, next) => {
    // ctx.request.body
    // username     password
    try {
        //使用中间件提供的方法
        ctx.validateBody('username')
            .required('用户名是必须的') //只要求有 username 字段,可以为空
            .isString() //确保输入的字段是字符串,或者可以转换成字符串
            .trim() //去掉前后空格
            .isLength(6, 12, '用户名必须是6~12位') //限制长度

        ctx.validateBody('email')
            .optional()
            .isString()
            .trim()
            .isEmail('非法的邮箱格式')

        ctx.validateBody('pwd1')
            .required('密码是必填项')
            .isString()
            .isLength(6, 16, '密码必须是6~16位字符')

        ctx.validateBody('pwd2')
            .required('密码是必填项')
            .isString()
            .eq(ctx.vals.pwd1, '两次密码不一致')

        // 校验数据库是否存在相同值
        // ctx.validateBody('username')
        // .check(await db.findUserByUsername(ctx.vals.username),'Username taken')
        // ctx.validateBody('username').check('tom', '用户名已存在')

        //如果代码执行到这里,校验通过
        // 校验器会用净化后的值填充·ctx.vals·对象
        console.log(ctx.vals);

        ctx.body = {
            ok: 1
        }
    } catch (error) {
        // 校验异常特别判断
        if (error instanceof bouncer.ValidationError) {
            ctx.status = 400
            ctx.body = '校验失败:' + error.message;
            return;
        }
        throw error
    }
})