ExodusMovement / schemasafe

A reasonably safe JSON Schema validator with draft-04/06/07/2019-09/2020-12 support.
https://npmjs.com/@exodus/schemasafe
MIT License
161 stars 12 forks source link

Format function doesn't works for numbers #159

Open avkos opened 1 year ago

avkos commented 1 year ago

I want to use the custom format function, but it doesn't call if the data has a number type.

example:


var validate = validator({
    type: 'array',
    items: [{ $id:'/0/0', format: 'uint' }] ,
    maxItems: 1,
    minItems: 1
}, {
    includeErrors: true,
    formats: {
        'uint': (d) => {
            console.log('validator works')
            return d>0
        }
    },
});

console.log(validate([-2])); // true -  formator uint doesn't call
console.log(validate(['-2'])); // false - formator uint calls

Expect behavior: Formats works for numbers and any other types

ChALkeR commented 1 year ago

Hm. While the specs say that built-in formats apply only to strings and ignore/always pass on non-string values, that doesn't necessary mean that custom formats should be only applicable to strings.

That means that changing the impl in a way that will attempt to run custom format validators on everything including non-strings is acceptable per spec.

That might cause backwards incompatibility though (and might be unexpected in some cases), so likely shouldn't be the default behavior, but rather an option.

Will work on this.

ChALkeR commented 1 year ago

That said, the schema you provided looks problematic as it lacks type checks. I'll think if there could be a way to reduce the probability of mistakes here (though strong mode should help).

ChALkeR commented 1 year ago

Perhaps adding a separate option for generic formats that would enable this behavior explicitly would be a non-dangerous path.