zoukankan      html  css  js  c++  java
  • 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;
    }

    .

  • 相关阅读:
    Gradle with Kotlin (二) 项目、Java项目、父子、同级共享代码
    Gradle with Kotlin (一) 安装、DSL、任务、插件
    辛弃疾
    Remote Method Invoke
    Webpack (一) 选项和配置
    《芙蓉女兒誄》
    js 原型链之我见
    js 库
    Gradle
    Spring Boot 入门
  • 原文地址:https://www.cnblogs.com/crazycode2/p/11072410.html
Copyright © 2011-2022 走看看