TypeOrm
  • Getting Started
  • About
  • Connection
    • Working with Connection
    • Using ormconfig.json
    • Connection Options
    • Multiple connections
    • Connection APIs
  • Entity
    • What is Entity?
    • Embedded Entities
    • Entity Inheritance
    • Tree Entities
    • View Entities
    • Separating Entity Definition
  • Relations
    • What are Relations?
    • One-to-One
    • Many-to-one and One-to-Many
    • Many-to-Many
    • Eager and Lazy Relations
    • Relations FAQ
  • Entity Manager and Repository
    • What is EntityManager
    • Working with Repository
    • Find Options
    • Custom Repositories
    • Entity Manager API
    • Repository API
  • Query Builder
    • Select using Query Builder
    • Insert using Query Builder
    • Update using Query Builder
    • Delete using Query Builder
    • Working with Relations
    • Caching Results
  • Advanced Topics
    • Using CLI
    • Logging
    • Listeners and Subscribers
    • Indices
    • Transactions
    • Migrations
  • Guides
    • Active Record vs Data Mapper
    • Working with MongoDB
    • Using Validation
    • Example with Express
    • Usage with JavaScript
    • Migration from Sequelize
  • Help
    • FAQ
    • Supported Platforms
    • Decorators reference
    • Roadmap
    • Changelog
Powered by GitBook
On this page

Was this helpful?

  1. Guides

Using Validation

PreviousWorking with MongoDBNextExample with Express

Last updated 4 years ago

Was this helpful?

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

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 {getManager} from "typeorm";
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 getManager().save(post);
}
class-validator