From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Validating field using @IsEnum() validator

Validating field using @IsEnum() validator

In NestJS, isEnum is a built-in validation decorator provided by the ClassValidator library. It is used to validate whether a property's value is a valid member of an enum. Let's implement it practically. Inside the AuthTTO class, I am adding a new field country of type string and I will give the is enum validator on the country field. Now there are two ways we can pass the enum in the validator. First is we directly provide an array containing the values. For example, let me give an array of countries, India, USA, UK, and Australia. So the isenum validator will now only check for the values provided in the array. Let's update the controller file. I'll add the country, userdata.country. Let's go to the postman now. And in the request body, I'll give the country property and the value ind. And when we make the request, we get the value returned. If I pass a different country or any random string value, then it will show the validation error that it is expecting the country must be from…

Contents