Type coercion disables strict validating of non-finite numbers in object schema
What version of Ajv are you using? Does the issue happen if you use the latest version?
8.12.0, yes
Ajv options object
{coerceTypes: true, strict: true}
JSON Schema
I used this Typebox schema
const PositiveIntegerObjSchema = typebox.Type.Object({
id: typebox.Type.Integer({ minimum: 0 }),
});
Sample data
[
{"id": "Infinity"},
{"id": "-Infinity"}
]
const typebox = require("@sinclair/typebox");
const Ajv = require("ajv");
new Ajv();
const ajv = new Ajv({coerceTypes: true, strict: true});
const PositiveIntegerObjSchema = typebox.Type.Object({
id: typebox.Type.Integer({ minimum: 0 }),
});
function compile(input) {
console.log(
`${input.id} (${typeof input.id}): ${ajv.compile(PositiveIntegerObjSchema)(
input
)}`
);
}
const idValues = [
Infinity,
-Infinity,
"Infinity",
"-Infinity",
42,
"42",
NaN,
"NaN",
];
idValues.forEach((val) => compile({ id: val }));
Validation result, data AFTER validation, error messages
Infinity (number): false
-Infinity (number): false
Infinity (string): true
-Infinity (string): true
42 (number): true
42 (string): true
NaN (number): false
NaN (string): false
What results did you expect? Infinity (number): false -Infinity (number): false Infinity (string): false -Infinity (string): false 42 (number): true 42 (string): true NaN (number): false NaN (string): false
Are you going to resolve the issue?
If I'm able. Currently, Resorting to Regex Type for reliable integer validation.
please make sample without typebox, just as plain json.
I'm happy to take a look at this but I really need an example without other dependencies. Please use this https://runkit.com/jasoniangreen/ajv-issue - it doesn't seem to support > 8.12 but that should be fine for most cases.
Close for lack of response.
@jasoniangreen @epoberezkin Could this be reopened, please? Here's the test without Typebox, and the issue still exists with 8.17.1
const Ajv = require('ajv'); // tested with 8.17.1
const ajv = new Ajv({ coerceTypes: true });
const PositiveIntegerObjSchema = {
type: 'object',
properties: {
id: {
type: 'integer',
minimum: 0
}
}
};
function test(input) {
console.log(`${input.id} (${typeof input.id}): ${ajv.compile(PositiveIntegerObjSchema)(input)}`);
}
const idValues = [
Infinity, // false -> ok
-Infinity, // false -> ok
'Infinity', // true -> NOT OK
'-Infinity', // true -> NOT OK
42, // true -> ok
'42', // true -> ok
NaN, // false -> ok
'NaN' // false -> ok
];
idValues.forEach(val => test({ id: val }));