2016-07-26 7 views
0

Ich versuche, validate() in meinem Modell zu verwenden, um zu überprüfen, ob der im POST übergebene Parameter gültige ID des zugehörigen Modells enthält. Hier ist der Code, den ich in meiner Person.js Datei geschrieben:Loopback benutzerdefinierte Validierung

'use strict'; 

module.exports = function(Person) { 
    Person.validate('countryId', function(err) { 
    var Country = Person.app.models.Country; 
    var countryId = this.countryId; 
    if (!countryId || countryId === '') 
     err(); 
    else { 
     Country.findOne({where: {id: countryId}}, function(error, result) { 
     if (error || !result) { 
      err(); 
     }; 
     }); 
    }; 
    }); 
}; 

Person ist Nachkomme von User-Modell und wenn ich versuche Modell mit anderem fehlerbehaftete Bereich zu erstellen (wie doppelte E-Mail zum Beispiel), dann enthält die Antwort die Fehler Nachricht mit meinem Scheck verbunden. Mache ich etwas falsch oder ist das ein Fehler?

Antwort

0

Sie benötigen einen asynchronen Validierung verwenden, zum Beispiel:

'use strict'; 

module.exports = function(Person) { 

    Person.validateAsync('countryId', countryId, { 
     code: 'notFound.relatedInstance', 
     message: 'related instance not found' 
    }); 

    function countryId(err, next) { 
     // Use the next if countryId is not required 
     if (!this.countryId) { 
      return next(); 
     } 

     var Country = Person.app.models.Country; 

     Country.exists(this.countryId, function (error, instance) { 
      if (error || !instance) { 
       err(); 
      } 
      next(); 
     }); 
    } 

};