4.0.0 • Published 10 months ago

@cherry0311/ren-plugin v4.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

egg-validate

NPM version build status Test coverage David deps Known Vulnerabilities npm download

基于 parameter 提供数据校验方法。

安装

$ npm i egg-validate --save

配置

// config/plugin.js
exports.validate = {
  enable: true,
  package: 'egg-validate',
};

egg-validate 支持 parameter 的所有配置项,查看 parameter 文档 获取配置项的更多信息。

// config/config.default.js
exports.validate = {
  // convert: false,
  // validateRoot: false,
};

使用方法

  • ctx.validate(rule[, data])

默认验证请求 Body

const createRule = {
  name: 'string',
  age: 'int',
  gender: ['male', 'female', 'unknow'],
};

exports.create = function* () {
  // 校验失败自动返回 422 响应
  this.validate(createRule);
  // 可以传递自己处理过的数据,默认使用 this.request.body
  // this.validate(createRule[, your_data]);
  // 校验通过
  this.body = this.request.body;
};

如果验证失败,会返回:

HTTP/1.1 422 Unprocessable Entity

{
  "message": "Validation Failed",
  "errors": [
    {
      "field": "username",
      "code": "missing_field",
      "message": "username required"
    }
  ]
}

addRule

  • app.validator.addRule(rule, checker)

validate 除了在 context 上增加了 validate 方法外,还在 application 上增加了一个 validator 对象, 可以通过 app.validator.addRule(rule, checker) 增加自定义的检查类型。

  • app.js
module.exports = app => {
  app.validator.addRule('json', (rule, value) => {
    try {
      JSON.parse(value);
    } catch (err) {
      return 'must be json string';
    }
  });
};
  • 然后在 controller 中使用
const createRule = {
  username: {
    type: 'email',
  },
  password: {
    type: 'password',
    compare: 're-password'
  },
  addition: {
    required: false,
    type: 'json' // 自定义的 json 类型
  },
};

exports.create = function* () {
  this.validate(createRule);
  this.body = this.request.body;
};
4.0.0

10 months ago

3.0.2

10 months ago

3.0.1

10 months ago

3.0.0

10 months ago

2.0.0

10 months ago

1.0.9

10 months ago

1.0.8

10 months ago

1.0.7

10 months ago

1.0.6

10 months ago

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago