Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating String Literal Type with class-validator

I have this type:

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

With which class-validator decorator can I validate that a property has one of those values?

import { IsEmail, IsString, Contains } from "class-validator";

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

export class AddBranchOperatorRequest extends User {

    @IsEmail()
    email: string;

    @Contains(BranchOperatorRole )
    role: BranchOperatorRole;

}

like image 850
Radecom System Avatar asked Nov 16 '25 03:11

Radecom System


1 Answers

const roles = ['none', 'seller', 'operator', 'administrator'] as const;
export type BranchOperatorRole = typeof roles[number];

export class AddBranchOperatorRequest extends User {

    @IsEmail()
    email: string;

    @IsIn(roles)
    role: BranchOperatorRole;

}
like image 79
Nikita Avatar answered Nov 18 '25 20:11

Nikita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!