ali-pourzahmatkesh
ali-pourzahmatkesh

Reputation: 113

sails.js model validation in bootstrap function

I have a model in sails.js and before creating a new record, I want to validate the data that I wanna insert in model.

this is my model for example :

module.exports = {
  attributes: {
        levelNumber : {
          type : 'string',
          defaultTo : '',
          required : true,
          unique : true
        }
  }
}

and this is my code that I put in bootstrap.js to run :

  MODELNAME.validate({
    levelNumber: 10
  }, function(err){
    if (err && err.invalidAttributes) {
      console.log(err.invalidAttributes);
    } else {
      // model is valid
      console.log('validate');
    }
});

it always return "validate" and never return error in validation!!!!

my questions is : 1 - how we can validate and input json for a model before creating it ?

thx

Upvotes: 1

Views: 365

Answers (2)

Ryan W
Ryan W

Reputation: 6173

You can simply add beforeCreate function to your Model definition under api/models

your model will look like this

module.exports = {
  attributes: {
     .....
  },
  beforeCreate: function(values, next) {
    // Validate the values HERE!!
  }
};

Upvotes: 1

Boris Zagoruiko
Boris Zagoruiko

Reputation: 13164

Is there a reason to put application logic to bootstrap.js? The fact is sails executed it before the app is lifted, so it is not strange that something is not working correctly.

Upvotes: 1

Related Questions