Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

loopbackjs - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
        ]
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...