» npm install class-validator-extended
Add @Type(() => AuthParam) to your array and it should be working. Type decorator is required for nested objects(arrays). Your code becomes
import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';
import { AuthParam } from './authParam.model';
import { Type } from 'class-transformer';
export class SignInModel {
@IsArray()
@ValidateNested({ each: true })
@ArrayMinSize(2)
@ArrayMaxSize(2)
@Type(() => AuthParam)
authParameters: AuthParam[];
}
Be careful if you are using any exception filter to modify the error reponse. Make sure you understand the structure of the class-validator errors.
I Know I Am Late But Facing Some Issue With Type, Then Try Another Way To Implement This:
export class AuthParam {
@IsNumber()
id: number;
@IsString()
type: string;
@IsString()
value: string;
}
Validation function
@ValidatorConstraint()
export class IsAuthArray implements ValidatorConstraintInterface {
public async validate(authData: AuthParam[], args: ValidationArguments) {
return Array.isArray(authData) && authData.reduce((a, b) => a && (typeof b.id === "number") && typeof b.type === "string" && typeof b.field === "string", true);
}
}
export class SignInModel {
@IsNotEmpty()
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(2)
@Validate(IsAuthArray, {
message: "Enter valid value .",
})
authParameters: AuthParam[];
}
Maybe It Will Help Someone 😃
With class-validator you have the options of Conditional Validation and of Group Validation, or you could always create a custom pipe and use AJV as you are used to. For the conditional validation you could create validations based on type and then let class-validator take care of the rest
You have to create a custom validator for that. The docs are pretty good: https://github.com/typestack/class-validator#custom-validation-classes
When you create your custom validator class, in your implementation of validate you can access the other parameter beeing validated in the args argument. Just write your if statements and return false if they are not met. You can even return your custom error messages and implement your own decorator.
» npm install class-validator-jsonschema