Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a custom validation with options for Loopback?

Is there a prescribed way to create a custom validator in loopback? As an example, assume that I want to create something like:

Validatable.validatesRange('aProperty', {min: 0, max: 1000})

Please note that I am aware of:

Validatable.validates(propertyName, validFn, options)

The problem I have with validates() is that validFn does not have access to the options. So, I'm forced to hard code this logic; and create a custom method for every property that needs this type of validation. This is undesirable.

Similarly, I am familiar with:

Model.observes('before save', hookFn)

Unfortunately, I see no way to even declare options for the hookFn(). I don't have this specific need (at least, not yet). It was just an avenue I explored as a possible alternative to solve my problem.

Any advice is appreciated. Thanks in advance!

like image 449
Cliff Chaney Avatar asked Sep 17 '15 13:09

Cliff Chaney


1 Answers

There is a mention of how to do this over at https://docs.strongloop.com/display/public/LB/Validating+model+data

You can also call validate() or validateAsync() with custom validation functions.

That leads you to this page https://apidocs.strongloop.com/loopback-datasource-juggler/#validatable-validate

Which provides an example.

I tried it out on my own ...

  Question.validate('points', customValidator, {message: 'Negative Points'});
  function customValidator(err) {
    if (this.points <0) err();
  }

And since that function name isn't really used anywhere else and (in this case) the function is short, I also tried it out with anonymous function:

Question.validate('points', 
        function (err) { if (this.points <0) err(); }, 
        {message: 'Question has a negative value'})

When points are less than zero, it throws the validation error shown below.

{
  "error": {
    "name": "ValidationError",
    "status": 422,
    "message": "The `Question` instance is not valid. Details: `points` Negative Points (value: -100).",
    "statusCode": 422,
    "details": {
      "context": "Question",
      "codes": {
        "points": [
          "custom"
        ]
      },
      "messages": {
        "points": [
          "Negative Points"
        ]
      }
like image 168
user465342 Avatar answered Oct 25 '22 01:10

user465342