Last active
January 1, 2016 17:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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