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

前端 未结 3 677
星月不相逢
星月不相逢 2020-12-31 16:13

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 validat

相关标签:
3条回答
  • 2020-12-31 16:40

    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);
    }
    .....
    
    0 讨论(0)
  • 2020-12-31 16:55

    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

    0 讨论(0)
  • 2020-12-31 16:56

    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;
        });
      });
    }
    ...
    
    0 讨论(0)
提交回复
热议问题