到目前为止,在 NestJS 中对对象数组验证的开箱即用支持还很少。
请看看我的解决方案:
要点是编写然后使用您的自定义IsArrayOfObjects
装饰器,该装饰器将包含来自模块的验证逻辑 +@Type
装饰器。class-transformer
import { Type } from 'class-transformer';
import {
IsString,
registerDecorator,
ValidateNested,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
export function IsArrayOfObjects(validationOptions?: ValidationOptions) {
return (object: unknown, propertyName: string) => {
registerDecorator({
name: 'IsArrayOfObjects',
target: object.constructor,
propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any): boolean {
return (
Array.isArray(value) &&
value.every(
(element: any) =>
element instanceof Object && !(element instanceof Array),
)
);
},
defaultMessage: (validationArguments?: ValidationArguments): string =>
`${validationArguments.property} must be an array of objects`,
},
});
};
}
假设我们有这个NestedDTO
:
export class NestedDTO {
@IsString()
someProperty: string;
}
然后我们可以简单地使用它来定义如下:
@IsArrayOfObjects()
@ValidateNested()
@Type(() => NestedDTO)
nested: NestedDTO[];
但是,此解决方案将允许传递空数组。IsArrayOfObjects
然后,您可以在like中添加额外条件value.length > 0
并更正其defaultMessage
.