class-validator case-insensitive enum validation?
Asked Answered
K

3

16

I have anum like this:

export enum UserRole {
  USER,
  ADMIN,
  BLOGGER
}

and create.user.dto like this

import { IsEmail, IsEnum, IsNotEmpty, IsOptional } from 'class-validator';
import { UserRole } from './user.entity';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  firstName: string;

  @IsNotEmpty()
  lastName: string;

  @IsOptional()
  username: string;

  @IsOptional()
  @IsEnum(UserRole)
  role: UserRole;

  @IsNotEmpty()
  password: string;
}

Now role validation does not fail if I only post the role uppercase('ADMIN','USER') or 'BLOGGER'.

How to make class-validator not case sensitive? I mean, validate true also for 'admin' 'aDmIn'.

Kentish answered 19/4, 2020 at 20:54 Comment(1)
ENUM will not do this, and i dont think that @IsIn(Array) is case-insensitive, you have to write custom validator, where you can use this condition array.includes(incoming-value.toLowercase)Nottingham
R
13

then you need a regexp validation via @Matches.

  @IsOptional()
  @Matches(`^${Object.values(UserRole).filter(v => typeof v !== "number").join('|')}$`, 'i')
  role: UserRole;

the final rule is /^USER|ADMIN|BLOGGER$/i, where i ignores the case.

Retroaction answered 19/4, 2020 at 21:14 Comment(0)
G
10

For what it's worth, you could also use class-validator's @Transform decorator to match your enum casing.

export enum UserRole {
 USER = "user",
 ADMIN = "admin",
 BLOGGER = "blogger"
}

Then in your DTO:

@IsOptional()
@Transform(({ value }) => ("" + value).toLowerCase())
@IsEnum(UserRole)
role: UserRole;

Worked for me with "class-validator": "^0.14.0"

Gulledge answered 14/7, 2023 at 13:54 Comment(0)
D
2

your enum should like this

export enum UserRole {
  USER = "USER",
  ADMIN = "ADMIN",
  BLOGGER = "BLOGGER"
}

is proven works in case-insensitive or vice versa

Diplex answered 15/5, 2022 at 10:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.