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; }
.