Skip to content

New Validator Decorator: @IsEnum #23

@waji-io

Description

@waji-io

I have created a custom validator that others might find useful as well.
It covers the use case of validating property values against an Enum or Enum-like Object.

export type ValidatorOptionType = {
    message?: string;
}

export const IsEnum = (enumOrEnumObject: Record<string, unknown>, { message }: ValidatorOptionType = {}): PropertyDecorator => {
  const enumValues: Set<unknown> = new Set(Object.values(enumOrEnumObject));
  const enumValuesString: string = Array.from(enumValues).join(', ');

  return createDecorator(
    (prop: unknown) => enumValues.has(prop),
    { errorMessage: message ? message : 'Property is limited to the following values: $constraint', 
     constraints: [enumValuesString] }
  );
};

The code above could be improved further by disallowing non-scalar properties like objects or arrays.

Here is an example of how to use it:

@IsEnum(GeneralStatusEnum)
status: GeneralStatusEnumType = GeneralStatusEnum.OPEN;

Below are some tests I did. It looks like working with both Enums and Objects.

export const TestEnumObject = {
    R: 'R',
    W: 'RW',
    D: 'RWD',
    A: 0,
    XX: true
} as const;

const objectValues: Set<unknown> = new Set(Object.values(TestEnumObject));
const objectValuesString: string = Array.from(objectValues).join(', ');
console.log(objectValuesString);
// --> R, RW, RWD, 0, true

export enum TestEnum {
    R = 'R',
    W = 'RW',
    D = 'RWD',
    A = 0
}

const enumValues: Set<unknown> = new Set(Object.values(TestEnum));
const enumValuesString: string = Array.from(enumValues).join(', ');
console.log(enumValuesString);

// --> A, R, RW, RWD, 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions