https://orkhan.gitbook.io/typeorm/docs/validation
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
}
Validation
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)
}
'프로그래밍 > TypeORM' 카테고리의 다른 글
[TypeORM] Relations (0) | 2023.09.04 |
---|---|
[TypeORM] Many-to-one / one-to-many relations (0) | 2023.09.04 |
[TypeORM] One-to-one relations (0) | 2023.09.03 |
[TypeORM] Find Options - Advanced options (0) | 2023.09.02 |
[TypeORM] Find Options - Basic Options (0) | 2023.09.02 |
댓글