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 optional fields

Validating optional fields

In certain scenarios, there are fields or properties which are not mandatory, that is they are optional. So even if we keep them empty, no validation is triggered. In NestJS, the isOptional validator is specifically used for this purpose. It is used to specify that a property in a DTO, data transfer object that is, is optional, meaning it may or may not be present in the payload being validated. So even if the property is missing, validation will still pass. Let's check an example. Below the date of birth property, let me give the phone property of type number. Let's make this property optional by giving the isOptional validator. This validator checks if value is missing, and if so, it ignores all validators as well. So now, even if we do not include the phone property in the payload, that is request body, then also the request will be carried out successfully. Not only that, even if we define multiple validators on this property like isNumber and maxLength, then also the request will…

Contents