验证器

借助 egg-validate 插件提供便捷的参数校验机制,帮助我们完成各种复杂的参数校验。

开启验证器:

config/plugin.js

exports.validate = {
  enable: true,
  package: 'egg-validate',
},

在控制器中:

app/controller/user.js

'use strict';
const Controller = require('egg').Controller;
const createRule = {
  username: {
    type: 'email',
  },
  password: {
    type: 'password',
    compare: 're-password',
  },
};
class PostController extends Controller {
  async create() {
    const ctx = this.ctx;
    try {
      ctx.validate(createRule);
      ctx.body = { success: true, msg: 'ok' };
    } catch (err) {
      ctx.logger.warn(err.errors);
      ctx.body = { success: false, msg: err.errors };
    }
  }
}
module.exports = PostController;

验证规则

参考: https://github.com/node-modules/parameter

通用规则

  • required 必传
  • type 验证类型
  • convertType 类型转换规则, 支持 int, number, string, boolean, function
  • default 默认值
  • widelyUndefined

type

  • int/integer [int]
  • string [string]
    • allowEmpty/empty
    • format [RegExp]
    • max
    • min
    • trim
  • boolean
  • array [array]
    • itemType 数组每一项的类型
    • rule
    • max
    • min
  • object
    • rule
  • enum
    • values [array]
  • id [string] 匹配格式 /^\d+$/
  • date [string] 匹配格式 YYYY-MM-DD
  • dateTime/datetime [string] 匹配格式 YYYY-MM-DD HH:mm:ss
  • number [number]
    • max
    • min
  • email [string]
    • allowEmpty 是否允许为空, 默认false
  • password [string]
    • compare 比较字段
    • max 最大长度
    • min 最小长度, 默认8
  • url [string]

简写

  • 'int' => {type: 'int', required: true}
  • 'int?' => {type: 'int', required: false }
  • 'integer' => {type: 'integer', required: true}
  • 'number' => {type: 'number', required: true}
  • 'date' => {type: 'date', required: true}
  • 'dateTime' => {type: 'dateTime', required: true}
  • 'id' => {type: 'id', required: true}
  • 'boolean' => {type: 'boolean', required: true}
  • 'bool' => {type: 'bool', required: true}
  • 'string' => {type: 'string', required: true, allowEmpty: false}
  • 'string?' => {type: 'string', required: false, allowEmpty: true}
  • 'email' => {type: 'email', required: true, allowEmpty: false, format: EMAIL_RE}
  • 'password' => {type: 'password', required: true, allowEmpty: false, format: PASSWORD_RE, min: 6}
  • 'object' => {type: 'object', required: true}
  • 'array' => {type: 'array', required: true}
  • [1, 2] => {type: 'enum', values: [1, 2]}
  • /\d+/ => {type: 'string', required: true, allowEmpty: false, format: /\d+/}

错误返回

出错时返回的格式, 例如:

{
  code: 'missing_field',
  field: 'name',
  message: 'required'
}
{
  code: 'invalid',
  field: 'age',
  message: 'should be an integer'
}

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress