0

I am trying to use validate() inside my model in order to verify if the param passed in POST contains valid ID of related model. Here is the code I written inside my Person.js file:

'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 is descendent of User model and when I try to create model with other errored field (like duplicate email for example) then the response contain the error message associated with my check. Am I doing something wrong or is this a bug?

dyleck
  • 1
  • 2

1 Answers1

0

You need use a asynchronous validation, for example:

'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();
        });
    }

};