fastest-validator
fastest-validator copied to clipboard
Feat: add array index in path
When validating an array of objects, when we use custom in nested rules, we cannot get the array element we are validating.
https://github.com/icebob/fastest-validator/blob/7b3557195393a83c09a1d3e581db898e1fcc26b4/lib/rules/array.js#L84-L88
An example of such a scheme:
const validator = {
some: {
type: 'array',
optional: true,
items: {
type: 'object',
props: {
start: {
type: 'string',
max: 8,
nullable: true,
custom: (
value: string | null,
_schema: unknown,
_path: unknown,
_parent: unknown,
_context: unknown
) => check(value),
},
end: {
type: 'string',
max: 8,
nullable: true,
custom: (
value: string | null,
_schema: unknown,
_path: unknown,
_parent: unknown,
_context: unknown
) => check(value),
},
},
},
},
}
The solution might be to change
const itemPath = path + "[]";`
on the
const itemPath = `${path}[${i}]`;
not sure if this would be a correct solution. @intech have you tested it ? does it work ? i also have the problem that in custom arrays there is no index reference, and this is a problem for particular validations.
@fernandodevelon
I didn't check, but I found out by tracing the code. I don’t remember how I decided in my case, but I did something differently. And the current problem is actually. I just forgot about it.
I did a test with the full example, activating debugging and tracing the custom call shows that itemPath does not have the references
itemPath = 'multiarray[][]'
this is the compiled code, where it calls the custom, no reference is passed to index i
I’ve been thinking about this issue, and after looking at the code, it’s not easily implementable unless the for loop saves the dynamic path in context.meta, for example.
However, it’s also true that each element of the array must be validated individually, otherwise the validation must be implemented at the highest level.
Therefore, I think we can close this issue.