Topics

Custom validation messages for sails js

//in /models/.js
 validationError(invalidAttributes, status, message) {
   WLValidationError = require('../../node_modules/sails/node_modules//lib///WLValidationError.js');
  return  WLValidationError({
      invalidAttributes: invalidAttributes,
      status: status,
      message: message
    }
  );
}
var User = {
  attributes: {
    //...
  },
  ownValidate:: function (values, update, cb) {
    //example of not allowed param on update
    //if it is an update then do not allow email param
    if (update && values.email) {
      return cb(validationError({
        email: [
          {
            message: 'Email is not allowed  updates.'
          }
        ]
      }, 400 /*status*/));
    }
    sails.models['user'].findOne(values.email).exec(function (err, user) {
      if (err) return cb(err);
      if (user) {
        return cb(validationError({
          email: [
            {
              value: values.email,
              rule: 'E_UNIQUE'
              /* unique  message is left for the default one here */
            }
          ]
        }, 409));
      }
    });
  },
  beforeCreate: function (values, cb) {
    return sails.models['user'].ownValidate(values, false, cb);
  },
  beforeUpdate: function (values, cb) {
    return sails.models['user'].ownValidate(values, true, cb);
  }
}

For blueprint custom validation

// For adding custom messages if  blueprint

// In reponses/badrequest.js
// after 
//  if (sails.config.environment === 'production') {
//    data = undefined;
//  }
// add
  if (data.invalidAttributes !== undefined) {
    var attributes = data.invalidAttributes;
    _.each(attributes, function (attribute, key) {
      _.each(attribute, function (properties) {
        var rule = properties.rule;
        var message = false;
        try {
          message = sails.__('validation.' + key + '.' + rule, key);
        }
        catch (e) {
        }

        try {
          message = sails.__('validation.' + rule, key);
        }
        catch (e) {
        }

        if (message && message != 'validation.' + rule && message != 'validation.' + key + '.' + rule) {
          properties.message = message;
        }
      });
    });
  }
  
  
  
  // In config/i18n.js 
  //add
  objectNotation: true
  
  // example :
  //In config/locales/en.json or your locale file
  //add
    "validation": {
      "isJson": "invalid JSON format in %s"
    }