Skip to content

Instantly share code, notes, and snippets.

@patelsan
Forked from johnnncodes/gist:8176318
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patelsan/b5d5c53da06be765a8f1 to your computer and use it in GitHub Desktop.
Save patelsan/b5d5c53da06be765a8f1 to your computer and use it in GitHub Desktop.
// 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