Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disable coercion enterily or selectively at global and local levels #1437

Open
wdavidw opened this issue Feb 8, 2021 · 4 comments
Open

Disable coercion enterily or selectively at global and local levels #1437

wdavidw opened this issue Feb 8, 2021 · 4 comments

Comments

@wdavidw
Copy link

wdavidw commented Feb 8, 2021

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

@ashwinchandran13
Copy link

where you able to solve this?

@wdavidw
Copy link
Author

wdavidw commented Aug 17, 2021

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

@epoberezkin
Copy link
Member

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...

@wdavidw
Copy link
Author

wdavidw commented Aug 23, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

3 participants