loopback icon indicating copy to clipboard operation
loopback copied to clipboard

How to change the value of property during validation?

Open bluestaralone opened this issue 12 years ago • 1 comments

In the setup method we do like this:

BookStore.setup = function() {

    // location
    function validateLocation(err) {
      // The latitude point in degrees. Range: -90 to 90.
      // The longitude point in degrees. Range: -90 to 90.
      if (this.location) {
        var abc = this.location.toString();
        var values = abc.split(",");
        if (values.length == 2 
            && validator.isNumeric(values[0]) 
            && validator.isNumeric(values[1])
            && values[0] >= -90 && values[0] <= 90
            && values[1] >= -90 && values[0] <= 90)
        {

          // convert to Point MongoDB-type
          this.location = { type: "Point", coordinates: [ validator.toFloat(values[0]), validator.toFloat(values[1]) ] };

          // fine
        }else {
          err();
        }
      }
    }

    BookStore.validate('location', validateLocation, {message: 'Invalid Location'});
  };

As you can see that we changed the "location" value of BookStore in that method to make sure it correct to save to mongodb but the changes only affected for creating BookStore and not for updating BookStore because in the Hook beforeSave(next, bookStore) as my check, only value of this.location was changed but bookStore.location was not. Finally, the object "bookStore" was saved to datasource but not for the object "this". So the "location" property was not changed as what i want. Please tell me why ?

bluestaralone avatar Sep 24 '14 08:09 bluestaralone

I don't think validators should modify the data, they are supposed to check whether a value is valid or not.

To sanitize/normalize data, one can use "before save" operation hook, see the docs.

bajtos avatar Jun 02 '16 12:06 bajtos