Can I define a custom validation with options for Loopback?

后端 未结 2 1322

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(\'         


        
2条回答
  •  臣服心动
    2020-12-17 03:55

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

提交回复
热议问题