类验证器忽略嵌套对象

时间:2020-02-19 18:59:37

标签: typescript nestjs class-validator

我正在为我的项目使用NestJs框架。在我的控制器中,我接受POST请求,并通过ValidationPipe将正文转换为我的CreateHouseDTO。 ValidationPipe正在使用白名单和转换。

当我尝试使用JSON这样的api时:

PdfConverter

这是我的应用程序记录的内容(console.log输出):

import java.io.*;
import java.math.BigInteger;

//needed jars: fr.opensagres.poi.xwpf.converter.core-2.0.2.jar, 
//             fr.opensagres.poi.xwpf.converter.pdf-2.0.2.jar,
//             fr.opensagres.xdocreport.itext.extension-2.0.2.jar,
//             itext-4.2.1.jar                                   
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;

//needed jars: apache poi and it's dependencies
//             and additionally: ooxml-schemas-1.4.jar 
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class XWPFToPDFConverterSampleMin {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // there must be a styles document, even if it is empty
  XWPFStyles styles = document.createStyles();

  // there must be section properties for the page having at least the page size set
  CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
  CTPageSz pageSz = sectPr.addNewPgSz();
  pageSz.setW(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
  pageSz.setH(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"

  // filling the body
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun title = paragraph.createRun();
  title.setText("gLETS GO");

  //document must be written so underlaaying objects will be committed
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  document.write(out);
  document.close();

  document = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()));
  PdfOptions options = PdfOptions.create();
  PdfConverter converter = (PdfConverter)PdfConverter.getInstance();
  converter.convert(document, new FileOutputStream("XWPFToPDFConverterSampleMin.pdf"), options);

  document.close();

 }
}

当我在嵌套对象中犯一些错误时,它甚至会验证嵌套对象。例如,如果我将 Floor 对象中的 name 属性设置为 Null 或某些不带引号的 number

是错误还是我做错了什么?请帮助我。

我的代码:

{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:5)

您应该这样做:

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    @Type(()=>CreateFloorDTO)
    public floors?: CreateFloorDTO[];
}