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