Using Validation

To use validation use class-validator.Example how to use class-validator with TypeORM:

  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. }

Validation:

  1. import {getManager} from "typeorm";
  2. import {validate} from "class-validator";
  3. let post = new Post();
  4. post.title = "Hello"; // should not pass
  5. post.text = "this is a great post about hell world"; // should not pass
  6. post.rating = 11; // should not pass
  7. post.email = "google.com"; // should not pass
  8. post.site = "googlecom"; // should not pass
  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. }