Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...