koa 项目实战(十)使用 validator 验证表单
1.安装模块
npm install validator -D
2.验证注册参数
根目录/validation/register.js
const Validator = require('validator'); const isEmpty = require('./is-empty'); module.exports = function validateRegisterInput(data) { let errors = {}; if (!Validator.isLength(data.name, { min: 2, max: 30 })) { errors.name = '名字的长度不能小于2位且不能超过30位'; } return { errors, isValid: isEmpty(errors) } }
根目录/validation/is-empty.js
const isEmpty = value => { return ( value == undefined || value === null || (typeof value === 'object' && Object.keys(value).length === 0) || (typeof value === 'string' && value.trim().length === 0) ); }; module.exports = isEmpty;
3.引入
根目录/routes/api/users.js
// 引入 input 验证密码 const validateRegisterInput = require('../../validation/register'); ... const { errors, isValid } = validateRegisterInput(ctx.request.body); // 判断是否验证通过 if (!isValid) { ctx.status = 400; ctx.body = errors; return; }
.