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: "ak@test.com"
},
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