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

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM