乐闻世界logo
搜索文章和话题

How to perform data validation in TypeORM?

2月17日 22:44

TypeORM validation can be implemented in the following ways:

  1. Use class-validator library: Install: npm install class-validator

    Use validation decorators in entities:

    typescript
    import { IsEmail, IsNotEmpty, Length } from 'class-validator'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() @IsNotEmpty() @Length(2, 50) name: string; @Column() @IsEmail() email: string; }
  2. Validate before saving:

    typescript
    import { validate } from 'class-validator'; const user = new User(); user.name = 'John'; user.email = 'invalid-email'; const errors = await validate(user); if (errors.length > 0) { console.log('Validation failed:', errors); }
  3. Use subscriber for automatic validation: Create a subscriber to automatically validate during BeforeInsert and BeforeUpdate.

  4. Database-level validation: Use database constraints with @Column options like nullable, unique, length, etc.

It's recommended to combine class-validator with database constraints to ensure data integrity and security.

标签:TypeORM