Search code examples
node.jstypescriptpostgresqlnestjstypeorm

class-validator doesn't validate entity


Can I use class-validator to validate Entity columns?

This doesn't validate the columns:

import { IsEmail } from 'class-validator';

@Entity()
export class Admin extends BaseEntity {

  @Column({ unique: true })
  @IsEmail()
  email: string;

}

However when I use the class-validator anywhere else in the code other than entities it validates properly and doesn't allow for bad inputs.

This works:

@InputType()
export class RegisterInput {

  @Field()
  @IsEmail()
  email: string;

}

Solution

  • The Entity should be clean

    @Entity()
        export class Admin extends BaseEntity {
        
          @Column({ unique: true })
          email: string;
        
        }
    

    While you define a DTO for checking the incoming request.

    export class AdminDto {
    
    @IsEmail() 
    email: string;
    
    }
    

    In your controller, you would check the incoming request with your AdminDto.

    @Controlller('route')
    export class AdminController {
    constructor(private yourService: yourserviceClass)
    
    @Post('/api')
    async createSomething(@Body('email', ValidationPipe) email: string){ //Your request body //would be checked against your DTO
    this.yourService.createMethod(email)
    }
    

    Hope this answers your question.