Skip to content

Instantly share code, notes, and snippets.

@johnnncodes
Last active January 1, 2016 17:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnnncodes/8176318 to your computer and use it in GitHub Desktop.
Save johnnncodes/8176318 to your computer and use it in GitHub Desktop.
Using custom validation messages in Sails.js by Rifat (itsrifat) - https://github.com/itsrifat Reference: https://github.com/balderdashy/sails/issues/1173#issuecomment-31327958
// make a module in node_modules named 'my-validation-utils'. create a index.js file there. and put the following content there:
var user = {
email:{
required:'Email Required',
email:'Should be an email'
},
name:{
required:'name required'
}
};
var product={
name:{
required:'Product name is required'
}
}
var validationMessages = {
user:user,
product:product
};
/**
* This function expects the name of the model and error.validationError
* and puts the user defined messages in error.validationError
*/
module.exports = function(model,validationError){
var messages = validationMessages[model];
for(key in messages){
var element = messages[key];
if(validationError[key]){
for(i in validationError[key]){
var err = validationError[key][i];
err.message = element[err.rule];
}
}
}
return validationError;
};
// Now in your controller do the following:
User.create(user).done(function (error, user) {
if (error) {
if (error.ValidationError) {
var validator = require('my-validation-utils');
var errors = validator('user',error.ValidationError);// puts the messages for model user
//now errors contains the validationErrors with user defined messages
}
} else {
//user is saved
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment