How to use NPM class-validator’s IsEnum to Enforce Class Attribute Values
I was recently building a chatbot for a messaging service. While building this service I found that many different types of messages shared a common “type” attribute with a preset list of possible values.
To make my app safer, I wanted to use the NPM class-validator package to ensure that the attributes in my classes had enforced rules. This was especially important for enforcing a preset list of values for the message object types. How do we use class-validator’s IsEnum decorator to enforce a preset of attribute values?
What is an enum?
Before implementing the IsEnum decorator, let’s discuss what an enum is. An enum is a user-defined type consisting of named constants. They help enforce the use of specific values for a field.
Say we have a Shirt class for a product in our clothing store. The Shirt class may have a size attribute that we have to manage. We don’t want to worry about random sizes being added in (what is a somewhat small shirt?). Enums create a set list of possible values so we don’t worry about imaginary sizes.
Enums also prevent inconsistent values. While the values of x-small, extra-small, x-s, and X-Small may have the same meaning, software engineers don’t want to manage all of those.
With an enum, we can create a set of case-sensitive values that a class attribute can have. Our enum for shirt sizes could look like this:
enum ShirtSize { ‘XS’, ’S’, ‘M’, ‘L’, ‘XL’, XXL’ }
If we assign an incorrect variable or attribute to this enum type it will reject the value.
How to use class-validator’s IsEnum decorator
Now that we understand what an enum is, let’s discuss how to validate with the class-validator’s IsEnum. Repeating our Shirt class example from the previous example we may have a class code looking like this:
import { IsString, IsNotEmpty, IsNumber } from 'class-validator'
class Shirt {
@IsString()
@IsNotEmpty()
color: string;
@IsNotEmpty()
@IsString()
size: string;
@IsNotEmpty()
@IsNumber()
price: number;
}
With this current code, our size value is for any string. This is not what we want. Instead, we want to ensure the size string is from a specific value set. We need to add the IsEnum decorator.
First, we need to add our enum definition. Once our ShirtSize enum is written we can assign it to the size attribute and then add the IsEnum decorator with a single argument of our enum.
import { IsEnum, IsString, IsNotEmpty, IsNumber } from 'class-validator'
// ES6 shorthand variable assignment. The strings values are the same as the
// provided keys
enum ShirtSize { XS, S, M, L, XL, XXL }
class Shirt {
@IsString()
@IsNotEmpty()
color: string;
@IsNotEmpty()
@IsEnum(ShirtSize)
size: ShirtSize;
@IsNotEmpty()
@IsNumber()
price: number;
}