ajv icon indicating copy to clipboard operation
ajv copied to clipboard

Disable coercion enterily or selectively at global and local levels

Open wdavidw opened this issue 4 years ago • 5 comments

What version of Ajv you are you using?

7.0.3

What problem do you want to solve?

In some circumstances, I wish to disable the coercion of a property. Take for example a timestamp defined as a number. If the user provides a boolean value, I expect a validation error to be thrown and not the value true to be converted to 1 which is a valid but incorrect timestamp:

const assert = require('assert')
const Ajv = require("ajv").default;

const data = {
  timestamp: true
};

const ajv = new Ajv({
  coerceTypes: true
})
validate = ajv.compile({
  "type": "object",
  "properties": {
    "timestamp": {
      "type": "integer"
    }
  }
})
error = validate(data)
// Expect an error instead of `1`
assert.equal(data.timestamp, 1)

What do you think is the correct solution to problem?

My expectation is the ability to entirely or selectively disable some coercion rules, either at a global level when AJV is instantiated or at a local level when the property is defined.

At a global level:

const ajv = new Ajv({
  coerceTypes: {
    // all coercion rules are enabled by default beside the ones declared:
    boolean_to_integer: false
  }
})

At a local level:

ajv.compile({
  "type": "object",
  "properties": {
    "timestamp": {
      "coercion": false
      "type": "integer"
    }
  }
})

Will you be able to implement it?

Maybe with some guidelines

wdavidw avatar Feb 08 '21 16:02 wdavidw

where you able to solve this?

ashwinchandran13 avatar Aug 17 '21 11:08 ashwinchandran13

No, there hasn't been any feedback for now.

wdavidw avatar Aug 17 '21 11:08 wdavidw

To be honest I am not very supportive of this feature - it would add a lot of complexity, and there doesn't seem to be a lot of interest...

epoberezkin avatar Aug 22 '21 19:08 epoberezkin

Would it be possible to simply expose a hook where we could implement our own coercion rule, I have many situation where implementing my own coersion or no coersion at all would be trivial if i could just plug my own function.

wdavidw avatar Aug 23 '21 17:08 wdavidw

Could this requested custom coercion on a specific level be achieved with custom keywords I wonder?

jasoniangreen avatar Jun 22 '24 08:06 jasoniangreen