简体   繁体   English

如何在Sails.js中提供自定义模型验证消息?

[英]How to provide custom model validation message in Sails.js?

How to provide custom model validation message in Sails.js? 如何在Sails.js中提供自定义模型验证消息?

The validation messages returned by Sails.js is not user friendly so I wanted to provide a custom validation message for rules like required, minLength etc... but don't really know how. Sails.js返回的验证消息不是用户友好的,所以我想为需要的规则,minLength等提供自定义验证消息......但实际上并不知道如何。 It's not in the docs and I also checked the docs of Anchor.js w/c is the validator used by Sails but its also not there. 它不在文档中,我也检查了Anchor.js的文档w / c是Sails使用的验证器,但它也不存在。

UPDATE: 更新:

Haven't got a response last week so I implemented my own solution, wanted to share it since it might be useful for others - How I use custom validation messages in Sails.js 上周没有回复,所以我实现了自己的解决方案,希望分享它,因为它可能对其他人有用 - 我如何在Sails.js中使用自定义验证消息

Another alternative and better way is to use the solution of @Rifat found in the comments below :) 另一种替代和更好的方法是使用下面评论中找到的@Rifat解决方案:)

Another very good alternative (credits to: sfb_ ) - https://gist.github.com/basco-johnkevin/8436644 另一个非常好的选择(信用:sfb_) - https://gist.github.com/basco-johnkevin/8436644

Since Sails.js doesn't yet support using custom model validation messages, we can use these solutions: 由于Sails.js尚不支持使用自定义模型验证消息,因此我们可以使用以下解决方案:

1) @johnkevinmbasco's solution 1) @ johnkevinmbasco的解决方案

2) @sfb_'s solution 2) @ sfb_的解决方案

3) @rifats solution 3) @rifats解决方案

I came up with modifying the badRequest response to overwrite the errors globally: 我想出了修改badRequest响应以覆盖全局错误:

/config/validationMessages.js

module.exports.validationMessages = {
  password: 'password and passwordConfirm do not match'
};

api/responses/badRequest.js

...
// Convert validation messages
if(data && data.code !== 'E_VALIDATION') {
  _.forEach(data.invalidAttributes, function(errs, fld) {
    data.invalidAttributes[fld] = errs.map(function(err) {
      if(sails.config.validationMessages[err.rule]) {
        err.message = sails.config.validationMessages[err.rule];
      }
      return err;
    });
  });
}
...

I am using sails-hook-validation 我正在使用sails-hook-validation

And made some improvements in responses/badRequest.js 并在response / badRequest.js中做了一些改进

.....
// If the user-agent wants JSON, always respond with JSON
if (req.wantsJSON) {
    if (data.code == 'E_VALIDATION' && data.Errors) {
        return res.jsonx(data.Errors);
    }
    return res.jsonx(data);
}
.....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM