Ankur
Ankur

Reputation: 3209

Loopback : Validate model from another model is not returning proper error message

I am validating model from another model like below

Model.addFavorite = function (data, callbackFn) {
        if (data) {
            var faviroteModel = this.app.models.Favorite;
            var objFavorite = new faviroteModel(data);
            objFavorite.isValid(function (isValid) {
                if (isValid) {
                    callbackFn(null, objFavorite);
                }
                else {                   
                    callbackFn(objFavorite.errors);
                }
            });
        }
        else callbackFn("Post data required", {});
    }

If i do this then I am getting error like below

{
  "error": {
    "statusCode": 500,
    "t": [
      "is not a valid date"
    ]
  }
}

It should be with error message like below

{
  "error": {
    "statusCode": 422,
    "name": "ValidationError",
    "message": "The `Favorite` instance is not valid. Details: `t` is not a valid date (value: Invalid Date).",
    "details": {
      "context": "Favorite",
      "codes": {
        "t": [
          "date"
        ]
      },
      "messages": {
        "t": [
          "is not a valid date"
        ]
      }
    }
  }
}

Can anyone tell me what am i missing here.

How can i achieve this.

Upvotes: 0

Views: 484

Answers (1)

user8120138
user8120138

Reputation:

https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/validations.js#L843

You might run into situations where you need to raise a validation error yourself, for example in a "before" hook or a custom model method.

    if (model.isValid()) {
        return callback(null, { success: true });
    }

    // This line shows how to create a ValidationError
    var err = new MyModel.ValidationError(model);
       callback(err);
    }

Upvotes: 1

Related Questions