cnodejs / egg-cnode

CNode 社区 Egg 版本
https://cnodejs.org/
MIT License
1.48k stars 285 forks source link

[TODO] egg-validate 集成 #70

Open thonatos opened 6 years ago

thonatos commented 6 years ago
// old
const title = validator.trim(ctx.body.title);
const tab = validator.trim(ctx.body.tab);
const content = validator.trim(ctx.body.t_content);

let editError;
if (title === '') {
  editError = '标题不能是空的。';
} else if (title.length < 5 || title.length > 100) {
  editError = '标题字数太多或太少。';
} else if (content === '') {
  editError = '内容不可为空';
}

// egg-validate
const RULE_CREATE = {
  title: {
    type: 'string',
    required: true,
    max: 100,
    min: 5,
  },
  content: {
    type: 'string',
    required: true,
  },
};

class TemplateController extends Controller {
  async create() {
    const { ctx } = this;
    ctx.logger.debug(ctx.request.body);
    ctx.validate(RULE_CREATE, ctx.request.body);
    // ...
  }
}
forl commented 6 years ago

已经在 #69 中引入了,但只在 POST topic/create 中使用了。还有遗留的工作是 render validate error.

sinchang commented 6 years ago

这一块有人在跟进吗?egg-validate 不能自定义错误提示文字?

thonatos commented 6 years ago

@sinchang addRule 实现才是正经做法(忽略我刚瞎写的)

const Parameter = require('parameter');
const parameter = new Parameter();

function checkAge(rule, value) {
  if (typeof value !== 'number') {
    return this.t('年龄必须是数字');
  }

  if (value > 100) {
    return this.t('年龄不能大于 200');
  }

  if (rule.rule) {
    return this.validate(rule.rule, value);
  }
}

parameter.addRule('age', checkAge)

const data = {
  name: 'foo',
  age: 'yibai',
  // age: 200,
};

const rule = {
  name: 'string',
  age: 'age',
};

const errors = parameter.validate(rule, data);

console.log(errors)
// [ { message: '年龄不能大于 200', code: 'invalid', field: 'age' } ]
// [ { message: '年龄必须是数字', code: 'invalid', field: 'age' } ]
atian25 commented 6 years ago

i18n 那个?我之前提了 RFC 但后面没时间搞

thonatos commented 6 years ago

@atian25 https://github.com/node-modules/parameter

atian25 commented 6 years ago

https://github.com/eggjs/egg/issues/1672

thonatos commented 6 years ago

好的好的,去看看,有时间搞一下~