使用 Validation

要使用验证,请使用class-validator。示例如何在 TypeORM 中使用 class-validator:

  1. import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
  2. import { Contains, IsInt, Length, IsEmail, IsFQDN, IsDate, Min, Max } from "class-validator";
  3. @Entity()
  4. export class Post {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. @Length(10, 20)
  9. title: string;
  10. @Column()
  11. @Contains("hello")
  12. text: string;
  13. @Column()
  14. @IsInt()
  15. @Min(0)
  16. @Max(10)
  17. rating: number;
  18. @Column()
  19. @IsEmail()
  20. email: string;
  21. @Column()
  22. @IsFQDN()
  23. site: string;
  24. @Column()
  25. @IsDate()
  26. createDate: Date;
  27. }

验证:

  1. import { getManager } from "typeorm";
  2. import { validate } from "class-validator";
  3. let post = new Post();
  4. post.title = "Hello"; // 不应该通过
  5. post.text = "this is a great post about hell world"; //不应该通过
  6. post.rating = 11; //不应该通过
  7. post.email = "google.com"; //不应该通过
  8. post.site = "googlecom"; //不应该通过
  9. const errors = await validate(post);
  10. if (errors.length > 0) {
  11. throw new Error(`Validation failed!`);
  12. } else {
  13. await getManager().save(post);
  14. }