Reputation: 475
I'm trying to validate a model and it's contents. However, because of the structure of loopbacks custom validation functions it's quite difficult to program more advanced logic than simple string validation.
Job.validate('job_definition, function(err){
//err();
//this will succeed in throwing error
Job.app.models.anotherModel.findOne({where:{name:this.job_definition.toolName}}, function(error, tool){
if(tool.aProperty === this.job_definition.aProperty){
//err();
//this will not succeed, validation script will exit before err() is thrown
}
});
}, {message: 'this is malformed'});
How can I get this validation function to 'wait' before exiting?
Upvotes: 1
Views: 674
Reputation: 10857
Here is an example using validateAsync (https://apidocs.strongloop.com/loopback-datasource-juggler/#validatable-validateasync). Note that you have to run err() when you want to fail validation.
module.exports = function(Person) {
function myCustom(err, done) {
console.log('async validate');
var name = this.name;
setTimeout(function() {
if(name == 'Ray') {
err();
done();
} else {
done();
}
}, 1000);
}
Person.validateAsync('name', myCustom, {message:'Dont like'});
};
Does this make sense? FYI, I could rewrite that if a bit nicer.
Upvotes: 3