# 使用校验

> 英文标题：Using Validation
> 官网原文：https://typeorm.io/docs/guides/validation
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 5 块

---

<!-- EN -->
# Using Validation

<!-- ZH -->
# 使用校验

<!-- EN -->
To use validation use [class-validator](https://github.com/pleerock/class-validator). Example how to use class-validator with TypeORM:

<!-- ZH -->
要使用校验，请使用 [class-validator](https://github.com/pleerock/class-validator)。在 TypeORM 中使用 class-validator 的示例：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
import {
    Contains,
    IsInt,
    Length,
    IsEmail,
    IsFQDN,
    IsDate,
    Min,
    Max,
} from "class-validator"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    @Length(10, 20)
    title: string

    @Column()
    @Contains("hello")
    text: string

    @Column()
    @IsInt()
    @Min(0)
    @Max(10)
    rating: number

    @Column()
    @IsEmail()
    email: string

    @Column()
    @IsFQDN()
    site: string

    @Column()
    @IsDate()
    createDate: Date
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
import {
    Contains,
    IsInt,
    Length,
    IsEmail,
    IsFQDN,
    IsDate,
    Min,
    Max,
} from "class-validator"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    @Length(10, 20)
    title: string

    @Column()
    @Contains("hello")
    text: string

    @Column()
    @IsInt()
    @Min(0)
    @Max(10)
    rating: number

    @Column()
    @IsEmail()
    email: string

    @Column()
    @IsFQDN()
    site: string

    @Column()
    @IsDate()
    createDate: Date
}
```

<!-- EN -->
Validation:

<!-- ZH -->
校验：

<!-- EN -->
```typescript
import { validate } from "class-validator"

let post = new Post()
post.title = "Hello" // should not pass
post.text = "this is a great post about hell world" // should not pass
post.rating = 11 // should not pass
post.email = "google.com" // should not pass
post.site = "googlecom" // should not pass

const errors = await validate(post)
if (errors.length > 0) {
    throw new Error(`Validation failed!`)
} else {
    await dataSource.manager.save(post)
}
```

<!-- ZH -->
```typescript
import { validate } from "class-validator"

let post = new Post()
post.title = "Hello" // 不应通过
post.text = "this is a great post about hell world" // 不应通过
post.rating = 11 // 不应通过
post.email = "google.com" // 不应通过
post.site = "googlecom" // 不应通过

const errors = await validate(post)
if (errors.length > 0) {
    throw new Error(`Validation failed!`)
} else {
    await dataSource.manager.save(post)
}
```
