Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class-validator case-insensitive enum validation?

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'.

like image 457
Hrant Nurijanyan Avatar asked Apr 19 '20 20:04

Hrant Nurijanyan


2 Answers

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.

like image 77
satanTime Avatar answered Sep 28 '22 17:09

satanTime


your enum should like this

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

is proven works in case-insensitive or vice versa

like image 23
DamarOwen Avatar answered Sep 28 '22 18:09

DamarOwen