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

白昼怎懂夜的黑 提交于 2019-12-18 13:16:54

问题


How to provide custom model validation message in 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. 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.

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

Another alternative and better way is to use the solution of @Rifat found in the comments below :)

Another very good alternative (credits to: sfb_ ) - https://gist.github.com/basco-johnkevin/8436644


回答1:


Since Sails.js doesn't yet support using custom model validation messages, we can use these solutions:

1) @johnkevinmbasco's solution

2) @sfb_'s solution

3) @rifats solution




回答2:


I came up with modifying the badRequest response to overwrite the errors globally:

/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;
    });
  });
}
...



回答3:


I am using sails-hook-validation

And made some improvements in responses/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);
}
.....


来源:https://stackoverflow.com/questions/20768102/how-to-provide-custom-model-validation-message-in-sails-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!