Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TODO] egg-validate 集成 #70

Open
thonatos opened this issue Mar 13, 2018 · 7 comments
Open

[TODO] egg-validate 集成 #70

thonatos opened this issue Mar 13, 2018 · 7 comments

Comments

@thonatos
Copy link
Member

thonatos commented Mar 13, 2018

// 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
Copy link
Contributor

forl commented Mar 14, 2018

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

@sinchang
Copy link
Contributor

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

@thonatos
Copy link
Member Author

thonatos commented Mar 21, 2018

@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
Copy link
Member

atian25 commented Mar 21, 2018

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

@thonatos
Copy link
Member Author

@atian25
Copy link
Member

atian25 commented Mar 21, 2018

eggjs/egg#1672

@thonatos
Copy link
Member Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants