Hi,
If I get the code correct each is not supported for custom validation classes, isnt it?
For example:
class Foo {
@Validate(MyValidationConstraint, { each: true })
bars: Array<Bar>
}
If I call validate on an instance of Foo my validate function gets an array passed.
Is this intended? I wonder because the type signatue of @Validate allows me to set each to true.
Thanks!
Each validation doesn't really behave that way. It won't assign the failed constraints to children errors, but rather to the decorated property itself.
Here's a test which could explain it better - it behaves the same regardless of whether each: true is set or not, the only difference is the error message.
import { ArrayNotEmpty, MaxLength, validateSync } from 'class-validator';
class List {
@ArrayNotEmpty()
@MaxLength(3, { each: true })
items: string[];
constructor(items: string[]) {
this.items = items;
}
}
test('should validate empty array', () => {
// given
const givenList = new List(['ok', 'long', 'ok', 'long']);
// when
const result = validateSync(givenList);
// then
console.log(result);
expect(result).toHaveLength(1);
expect(result[0].constraints).toHaveProperty('maxLength');
expect(result[0].children).toHaveLength(0);
});
IMHO the missing link is a class level validation constraint, like in Java Bean Validation. The current implementation is a bit limited when it comes to validating objects that can be used as either a property or an array item. When used in property mode, you can set the constraint easily. But when used as an array item, there is no way to validate nested objects as a whole. If someone knows how to work around it (or implement this feature), I'd be most grateful.
Currently custom constraint validation is applied to whole model array field instead of each array item despite each is set to true, which seems to be unexpected/inconsistent.
I've opened pull request that fixes this:
https://github.com/typestack/class-validator/pull/295
As a workaround you can avoid using { each: true } with custom constraint classes and validate whole array in the class.
Any update on this? At least documentation should be updated
Had the same problem when trying to validate an array of nested objects, already checked the fixes at #295 and they worked just fine.
Please try to merge it whenever you can.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Currently custom constraint validation is applied to whole model array field instead of each array item despite
eachis set to true, which seems to be unexpected/inconsistent.I've opened pull request that fixes this:
https://github.com/typestack/class-validator/pull/295
As a workaround you can avoid using
{ each: true }with custom constraint classes and validate whole array in the class.