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
4
@Entity()
5
export class Post {
6
7
@PrimaryGeneratedColumn()
8
id: number;
9
10
@Column()
11
@Length(10, 20)
12
title: string;
13
14
@Column()
15
@Contains("hello")
16
text: string;
17
18
@Column()
19
@IsInt()
20
@Min(0)
21
@Max(10)
22
rating: number;
23
24
@Column()
25
@IsEmail()
26
email: string;
27
28
@Column()
29
@IsFQDN()
30
site: string;
31
32
@Column()
33
@IsDate()
34
createDate: Date;
35
36
}
Copied!
Validation:
1
import {getManager} from "typeorm";
2
import {validate} from "class-validator";
3
4
let post = new Post();
5
post.title = "Hello"; // should not pass
6
post.text = "this is a great post about hell world"; // should not pass
7
post.rating = 11; // should not pass
8
post.email = "google.com"; // should not pass
9
post.site = "googlecom"; // should not pass
10
11
const errors = await validate(post);
12
if (errors.length > 0) {
13
throw new Error(`Validation failed!`);
14
} else {
15
await getManager().save(post);
16
}
Copied!
Copy link