Sails js model validation against database

I am writing a custom validation rule to check if "category_id" is actually passed to my create function or not.

types: {
  isValidCategoryId: function(id){
    return Category.findOne({id: id}).exec(function(err, user){
      if(err || !user)
        return false;
      else{
        return true;
      }  
  });
 }
},


attributes: {
  category_id : { isValidCategoryId: true, required: true, type: 'string' },
}

      

I understand that my custom validation function should return true, but in an asynchronous context this may not work, for example validating a value in the DB.

How do I write my own validation function to make it behave correctly?

+3


source to share


2 answers


I tried a part of banana solution. It didn't work, but at least it pointed me in the right direction.

According to the docs:

Validation rules can be defined as simple values ​​or functions (both synchronous and asynchronous) that return a value for validation.

So, one easy way to do it:

attributes: {
    category_id : {
        required: true,
        type: 'string',
        'true': function(cb) {
            Category.findOne({id: this.category_id}).exec(function(err, category){
                return cb(!err && category);
            });
        }
    }
}

      



As you can see, I'm just using the "true" validator here, but you can of course write your own validator to develop more advanced logic. The key point here is that your custom validators are not asynchronous, but your validation rules can be . Yes, the terminology is very confusing.

Here's another example with a custom validator:

attributes: {
    author: {
        required: true,
        type: 'string',
        canPost: function(cb) {
            Author.findOne(this.author).exec(function(err, author) {
                return cb(author);
            });
        }
    }
},
types: {
    canPost: function(id, author) {
        return author && author.canPost();
    }
}

      

Hope this makes sense. If not, see docs .

+6


source


You can pass a callback and return the result. This is a bit weird because it doesn't sound like the standard (err, result)

but uses instead (result)

. Try:



types: {
  isValidCategoryId: function(id, cb){
    return Category.findOne({id: id}).exec(function(err, user){
      if(err || !user)
        return cb(false);
      else{
        return cb(true);
      }  
  });
 }
},

      

+3


source







All Articles