class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

Validating OneToOne (or any other) relation using class-validator and ValidationPipe

Open PelayoChoya opened this issue 8 years ago • 3 comments

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Hi everyone,

I am having trouble when validating a OneToOne relation when receiving the request body. Class-validator does not check the fields that belong to the OneToOne relation. Having the following entities:

@Entity()
export class EntityA {
  @PrimaryGeneratedColumn()
  id: number;

 @Column({ nullable: true })
  @Length(2,5)
  sample: string;

  @OneToOne( type => EntityB)
  @JoinColumn()
  sample_one_to_one: EntityB;
}
@Entity()
export class EntityB {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  @Length(2,5)
  sample_data: string;
}

If I send the following JSON input:

{ "sample": "aaa"
  "sample_one_to_one": {
    "sample_data": "aaaaaaaaa"}
}

Using the following controller both entities are saved to the DB, however, an error should be risen since EntityB does not fulfill the Lenght requirement:

  @Post()
  @UsePipes(new ValidationPipe())
  async create(@Body() entityA: EntityA) {
    try{
      await this.entityBService.save(entityA.sample_one_to_one);
      return await this.entityAService.create(entityA);
    }
    catch (e)
    {
      throw e;
    }
  }

I used this as a fix:

@Post()
  @UsePipes(new ValidationPipe())
  async create(@Body() entityA: EntityA, @Body('entityB') entityB: EntityA) {
    try{
      await this.entityBService.save(entityB);
      return await this.entityAService.create(entityA);
    }
    catch (e)
    {
      throw e;
    }
  }

However this makes EntityB compulsory to appear in the request body.

Is there a standard way of validating relationships ? Or, if not, is there any way to specify a @Body parameter optional?

Thanks a lot

PelayoChoya avatar Aug 19 '18 11:08 PelayoChoya

@ValidateNested()

MichalLytek avatar Aug 19 '18 12:08 MichalLytek

Hi @PelayoChoya!

As @19majkel94 said, you need to use the @ValidatedNested decorator on your sample_one_to_one property.

@OneToOne( type => EntityB)
@JoinColumn()
@ValidateNested()
sample_one_to_one: EntityB;

NoNameProvided avatar Nov 05 '18 12:11 NoNameProvided

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Nov 12 '18 12:11 lock[bot]