TypeORM validation can be implemented in the following ways:
-
Use class-validator library: Install:
npm install class-validatorUse validation decorators in entities:
typescriptimport { IsEmail, IsNotEmpty, Length } from 'class-validator'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() @IsNotEmpty() @Length(2, 50) name: string; @Column() @IsEmail() email: string; } -
Validate before saving:
typescriptimport { 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); } -
Use subscriber for automatic validation: Create a subscriber to automatically validate during BeforeInsert and BeforeUpdate.
-
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.