4

It's my first time using sails and it looks like it's good but I run into a problem, is it possible to define a custom error message in sails model validation because it looks like the error message being returned is to technical and not user friendly.

Thanks

Update: https://gist.github.com/mikermcneil/8366092

ginad
  • 1,863
  • 2
  • 27
  • 42

2 Answers2

6

Here's another alternative:

/**
 * Takes a Sails Model object (e.g. User) and a ValidationError object and translates it into a friendly
 * object for sending via JSON to client-side frameworks.
 *
 * To use add a new object on your model describing what validation errors should be translated:
 *
 * module.exports = {
 *   attributes: {
 *     name: {
 *       type: 'string',
 *       required: true
 *     }
 *   },
 * 
 *   validation_messages: {
 *     name: {
 *       required: 'you have to specify a name or else'
 *     }
 *   }  
 * };
 *
 * Then in your controller you could write something like this:
 *
 * var validator = require('sails-validator-tool');
 *
 * Mymodel.create(options).done(function(error, mymodel) {
 *   if(error) {
 *     if(error.ValidationError) {
 *       error_object = validator(Mymodel, error.Validation);
 *       res.send({result: false, errors: error_object});
 *     }
 *   }
 * });
 *
 * @param model {Object} An instance of a Sails.JS model object.
 * @param validationErrors {Object} A standard Sails.JS validation object.
 *
 * @returns {Object} An object with friendly validation error conversions.
 */ 
module.exports = function(model, validationError) {
  var validation_response = {};
  var messages = model.validation_messages;
  validation_fields = Object.keys(messages);

  validation_fields.forEach(function(validation_field) {

    if(validationError[validation_field]) {
      var processField = validationError[validation_field];
      //console.log(processField);
      processField.forEach(function(rule) {
        if(messages[validation_field][rule.rule]) {
          if(!(validation_response[validation_field] instanceof Array)) {
            validation_response[validation_field] = new Array();
          }

          var newMessage={};
          newMessage[rule.rule] = messages[validation_field][rule.rule];
          validation_response[validation_field].push(newMessage);
        }
      });

    }
  });

  return validation_response;
};

Credits to: sfb_

John Kenn
  • 1,607
  • 2
  • 18
  • 31
  • Thanks, I've copied your suggestion but made a little modification to generate a generic message if you forgot to define a custom error message – ginad Mar 07 '14 at 15:04
  • @ginad - Cool. Can you share it to us? Thanks :) – John Kenn Apr 23 '14 at 01:07
  • 1
    @JohnKevinM.Basco, Can anyone confirm that error.ValidationError still exists in sails 11 the latest, because I am currently trying to use [sails-hook-validation](https://github.com/lykmapipo/sails-hook-validation) but it doesnt work, after debugging, I can see that the "error" object doesnt contain the "ValidationError" property. – hussainb Apr 04 '15 at 06:33
4

Here is an ugly fix:

make a folder 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 something like this:

User.create(user).done(function (error, user) {
  if (error) {
    if (error.ValidationError) {
      var validator = require('path/to/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
  }
});
Moinul Hossain
  • 2,176
  • 1
  • 24
  • 30