Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sails js model validation against database

Tags:

sails.js

I am writing a custom validation rule to check if the "category_id" passed to my create function is valid 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, like checking the value in DB.

How should I write my custom validation function to make it behave correctly?

like image 668
Ashis Maharana Avatar asked Dec 14 '25 07:12

Ashis Maharana


2 Answers

I tried particlebanana's solution. It didn't work but at least it pointed me in the right direction.

According to the docs:

Validation rules may be defined as simple values or functions (both sync and async) that return the value to test against.

So, one easy way to do this would be:

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 could of course write your own validator to work out some more advanced logic. The key here is that your custom validators aren't async, 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();
    }
}

Hopefully that makes sense. If not, See the docs.

like image 101
Arlen Anderson Avatar answered Dec 16 '25 23:12

Arlen Anderson


You can pass in a callback and return the result. It's a bit weird because it doesn't look like it follows the (err, result) standard but instead just uses (result). Give this a 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);
      }  
  });
 }
},
like image 36
particlebanana Avatar answered Dec 16 '25 21:12

particlebanana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!