Susmitha
Susmitha

Reputation: 267

Validation to have either one of the input as optional in nestjs

Recently I have started playing around nestjs and mongoose. I have come across a scenario where any of the two input fields should be optional.

I have my roles collection in mongodb and schema defined in mongoose. And for editing, I have written a DTO.

//Roles schema
export type RolesCollection = Role & Document;

@Schema({
  collection: 'roles',
  versionKey: false,
})
export class Role {
  @Prop()
  permissions: string[];

  @Prop({
    unique: true,
  })
  role: string;
}

export const RoleSchema = SchemaFactory.createForClass(Role);

//Roles DTO
export class EditRoleDto {
  @IsString()
  @IsOptional()
  role: string;

  @IsArray()
  @IsString({ each: true })
  @IsOptional()
  permissions: string[];
}

Here If I gave an empty body as an input to my edit controller, It is working. But I need to have any one of them should be given. How to do validation like that?

//My edit controller
async editRole(
    @Body() details: EditRoleDto,
    @Query('role') role: string,
    @Req() request: Request,
  ) {
    try {
      await this.editRoleSvc.editRole(role, details);
    } catch (err) {
      return errorChecks(err);
    }
  }

Upvotes: 0

Views: 2119

Answers (1)

user10057478
user10057478

Reputation:

export const RoleSchema = SchemaFactory.createForClass(Role);

//Roles DTO
export class EditRoleDto {
  @IsNotEmpty()
  @IsIn['roles', 'permissions']  
  use: <fieldName>; // role | permissions

  @ValidateIf(data => data.use == 'role')
  @IsString()
  @IsOptional()
  role: string;

  @ValidateIf(data => data.use == 'permissions')
  @IsArray()
  @IsString({ each: true })
  @IsOptional()
  permissions: string[];
}

How is this working??
You have a field in your DTO That will have two values either role or permissions and would not be empty. Based on the field use: One of them will be validated.

Upvotes: 3

Related Questions