acornejo / jjv

Javascript Library for Schema Validation
MIT License
198 stars 35 forks source link

mutual $data reference with default does not seem to work #49

Open fakraemer opened 9 years ago

fakraemer commented 9 years ago

This is a schema fragment I've written

"cpu" : {
  "additionalProperties": false,
  "properties": {
    "low": {
      "description": "The low threshold for the CPU utilization alarm.",
      "type": "integer",
      "default": 45,
      "minimum": 0,
      "maximum": { "$data": "1/high" }
    },
    "high": {
      "description": "The high threshold for the CPU utilization alarm.",
      "type": "integer",
      "default": 70,
      "minimum": { "$data": "1/low" },
      "maximum": 100
    }
  }
}

and I use the validator like this:

validator.addSchema('descriptor', JSON.parse(fs.readFileSync('./schema/schema.json')));
var errors = validator.validate('descriptor', opts.descriptor, {useDefault: true});

when I invoke this with both values set in the descriptor, the boundary checks work as expected. If I set e.g. only low to 80 (exceeding high) I would have expected the validation to fail but it passes. Am I using this incorrectly because it's a mutual reference or is the default not applied before this validation happens?

cristiano-belloni commented 9 years ago

+1

Even when it's not mutual, it does not work. Seems default is not applied before the validation happens. This is very inconvenient.

The workaround I found for this is to validate with useDefault and, if the validation does not get any errors, revalidate the same object and return the result.

The first pass will apply the defaults to the passed object and the second pass will validate a different object (the one containing defaults) against the validation.