TypeORM中文文档 v1.1
指南 / 使用校验
GitHub

使用校验

Using Validation 英文原文 Markdown

要使用校验,请使用 class-validator。在 TypeORM 中使用 class-validator 的示例:

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
}

校验:

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