Home > Software design >  Trying to validate an array of objects. Error: "an unknown value was passed to the validate fun
Trying to validate an array of objects. Error: "an unknown value was passed to the validate fun

Time:01-23

When i try to validate an array of objects of the body of some endpoint i am getting the error

an unknown value was passed to the validate function

Here i make the request using Insomnia

Request on Insomnia Client

This is the endpoint definition in the controller

@Controller('documents')
export class DocumentsController {
    @Post('factura')
    create(@Body() request : CreateFacturaRequest) : {params:Object,data:Object} {
        const params = {...don't matter...}
        const data = {...don't matter...}

        return {
            params,
            data
        };
    }
}

And this is the class CreateFacturaRequest who validates the body

enum TipoContribuyente {
    PersonaFisica=1,
    PersonaJuridica=2
}

enum TipoRegimen{
    RegimenTurismo=1,
    Importador=2,
    Exportador=3,
    Maquila=4,
    Ley6090=5,
    RegimenPequenhoProductor=6,
    RegimenMedianoProductor=7,
    RegimenContable=8
}

class ActividadEconomica {
    codigo: string
    descripcion: string
}

class Emisor {

    @IsDateString()
    fechaFirmaDigital: string

    @IsInt()
    @IsEnum(TipoContribuyente)
    tipoContribuyente: TipoContribuyente

    @IsInt()
    @IsEnum(TipoContribuyente)
    tipoRegimen: TipoRegimen

    @IsString()
    @IsNotEmpty()
    @Validate(IsRuc)
    ruc: string

    @IsString()
    @IsNotEmpty()
    razonSocial: string

    @IsString()
    @IsNotEmpty()
    nombreFantasia: string

    @IsInt()
    @IsNotEmpty()
    timbradoNumero: string

    @IsDateString()
    @IsNotEmpty()
    timbradoFecha: string

    @IsArray()
    @ValidateNested({each:true})
    @Type(() => ActividadEconomica)
    actividadesEconomicas: ActividadEconomica[]

}

class CreateFacturaRequest {
    @IsNotEmpty({message: 'Faltan datos del emisor'})
    @IsObject({message: 'Los datos del emisor deben enviarse en formato JSON'})
    @IsNotEmptyObject()
    @Type(()=>Emisor)
    @ValidateNested()
    emisor: Emisor
}

The error is caused by the actividadesEconomicas param

I expect to pass the validation because the body example in the screenshot is correct

CodePudding user response:

You're using class-validator 0.14.0. Nest uses 0.13.x and doesn't guarantee support for 0.14.x yet. You can downgrade class-validator to get a better error message and generally better support.

CodePudding user response:

I solved adding @IsString to each prop of the ActividadEconomica class

class ActividadEconomica {
    @IsString()
    codigo: string
    @IsString()
    descripcion: string
}
  • Related