1

I am working in NestJS Project, there is one situation where I need to implement conditional Validation.

So my Payload looks like this:

{
  user_id: "123"
  user_type: "M" //Value Can be M or F
  inner_details: {
     name: {
             firstname:"akshay",
             lastname:"nikte"
           },
     email: "[email protected]"
  },
  user_co: "Tesla"
}

So in above payload(body) there are some validation requirement as below:

If user_type = M then Firstname and Lastname both cannot be Empty

If user_type = F then Firstname cannnot be Empty but Lastname can be Empty

For this I created 3 DTO classes:

  Filename: create-user.dto.ts  
  export Class CreateUserDTO {
    
    @IsNotEmpty()
    @ApiProperty({
    required:true
    })
    user_id: string
    
    @IsNotEmpty()
    @ApiProperty({
    required:true
    })
    user_type: string
    
    @ValidateNested({each:true})
    @Type(()=>InnerDetailsDTO)
    inner_details: InnerDetailsDTO
    
    @IsNotEmpty()
    user_co: string
    
    }
    
    filname: inner-details.dto.ts
    export class InnerDetailsDTO {
    
     @ValidateNested({each: true})
     @Type: NameDTO
     name: NameDTO

     @IsNotEmpty
     @ApiProperty({
     required: true
     })
     email: string
    }

    filename name.dto.ts
    export class NameDTO {
    
       @IsNotEmpty()
       @ApiProperty({required: true})
       firstname: string

       @Validateif(check if UserType==="M") // How to access UserType from CreateUser DTO
       @IsNotEmprty()
       lastname: string  
    }

I have have 3 different DTOs in 3 different Files, how to use attribute from 1 DTO in another DTO ?

In my NameDTO I want apply conditional validation, when user_type==M then validate both Firstname and Lastname but when user_type==F Then only validate Firstname and not Lastname

1

1 Answer 1

1

I recommend yup. There you can also make conditional validation. But therefore you have to setup yup as a Validation Pipeline in Nestjs as well. See this npm module here. But this package is not really popular, so I would implement it myself (I actually did that and it works pretty well). This video explains it really good.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer but there is nothing wrong in having Multiple DTOs and Validation in that DTOs
I edited my answer since you really want to the validation in the DTO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.