Class-validator - Validate Array Of Objects


Answer :

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.


You can use the following:

validator.arrayNotEmpty(array); // Checks if given array is not empty.

validator.arrayMinSize(array, min); // Checks if array's length is at least `min` number.

(https://github.com/typestack/class-validator#manual-validation)

You may want to consider writing custom validator which would better reflect the business requirement you have.


 const param1: AuthParam = Object.assign(new AuthParam(), {   id: 1,   type: 'grant',   value: 'password' })  const param2: AuthParam = Object.assign(new AuthParam(), {   id: 1,   type: 4,   value: 'password' })  const signInTest = new SignInModel() signInTest.authParameters = [param1, param2]  validate(signInTest).then(e => {   console.log(e[0].children[0].children[0]) }) 

This works correctly, this is:

ValidationError {   target: AuthParam { id: 1, type: 4, value: 'password' },   value: 4,   property: 'type',   children: [],   constraints: { isString: 'type must be a string' } }  

so I may only assume that object which is being validated, is not an instance of AuthParam

const param2: AuthParam = {   id: 1,   type: 4,   value: 'password' } as any 

as expected, there aren't any decorators on this object (which may be true for Nest.js controllers and nested objects from body/req) - so validation is ignored.

Please check this (tl;dr - @Type decorator form class-transformer)


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?