Issue with format and oneOf
What version of Ajv are you using? Does the issue happen if you use the latest version? 4.10.0
Ajv options object (see https://github.com/epoberezkin/ajv#options):
ajv.addFormat('numeric', v => {
return !isNaN(parseFloat(v)) && isFinite(v)
})
JSON Schema (please make it as small as possible to reproduce the issue):
{
type: 'object',
additionalProperties: false,
required: [
'id',
],
properties: {
id: {
oneOf: [
{ format: 'numeric' },
{ type: 'array', items: { format: 'numeric' } },
]
},
}
}
Data (please make it as small as posssible to reproduce the issue):
{ id: ['1', '2'] }
Your code (please use options, schema and data as variables):
/* eslint-env mocha */
const assert = require('assert')
const Ajv = require('ajv')
const ajv = new Ajv()
ajv.addFormat('numeric', v => {
return !isNaN(parseFloat(v)) && isFinite(v)
})
describe('ajv lib', () => {
it('oneOf', () => {
const validator = ajv.compile({
type: 'object',
properties: {
id: {
oneOf: [
{ format: 'numeric' },
{ type: 'array', items: { format: 'numeric' } },
]
},
}
})
const validation = validator({ id: ['1', '2'] })
assert(validation, JSON.stringify(validator.errors))
})
})
Validation result, data AFTER validation, error messages:
AssertionError: [{"keyword":"oneOf","dataPath":".id","schemaPath":"#/properties/id/oneOf","params":{},"message":"should match exactly one schema in oneOf"}]
What results did you expect?
It should validate. format and oneOf doesn't seem to work properly/the way I thought it would.
Are you going to resolve the issue? If you confirm this is an issue I'll try to help out any way I can.
The schema { format: 'numeric' } does not require that the data is a string, it is valid for all other data types, including arrays. That's not an ajv issue, it's per spec.
You need to change it to { type: 'string', format: 'numeric' } (in both branches of oneOf).
Also anyOf is more efficient, so unless you need to ensure that only one subschema is valid (when it is not always the case from the design) it is better to use anyOf.
@epoberezkin Thank you for the quick response!
But if I manually run the numeric filter function with the data ['1', '2'], it returns false. What am I missing?
const v = ['1', '2']
console.log(!isNaN(parseFloat(v)) && isFinite(v))
-> false
Ah nevermind. Add custom format to validate strings
Format keyword is validated (and the function is called) only if the data is a string. All other data types pass format validation (the function is not called).