Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful.

The DTO file contains validation rules for checking properties:

export class UserActiveDTO {
    @IsNotEmpty()
    @IsString()
    readonly id: string;
  
    @IsNotEmpty()
    @IsString()
    readonly name: string;
  
    @IsNotEmpty()
    @IsString()
    readonly role: string;

    //.. other data validations
}

Within the service file, after retrieving the user from the database:

// Retrieving user information and attempting to validate it
let userCanBeActive: boolean = false;
try {
    const canActiveUser: UserActiveDTO = user;

    // Validating user using class-validator
    const vErrors = await validate(canActiveUser, {});
    if (vErrors.length > 0) throw vErrors;
    
    userCanBeActive = true;
  } catch (error) {
    userCanBeActive = false;
}

Despite implementing these validations, the code always sets userCanBeActive as true, even when properties mentioned in the DTO file are missing. What is the best practice for validating such scenarios in NestJS?

Answer №1

I'm confident that the variable user is not actually an instance of UserActiveDTO, but rather just meets the criteria of the interface. According to class-validator documentation, plain objects cannot be validated using this tool, so you'll need to convert the object into a class instance for the validate method to function correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

Is it possible to capture and generate an AxiosPromise inside a function?

I am looking to make a change in a function that currently returns an AxiosPromise. Here is the existing code: example(){ return api.get(url); } The api.get call returns an object of type AxiosPromise<any>. I would like to modify this function so ...

Error: JavaScript object array failing to import properly

In my code, I have an array of objects named trace which is defined as follows: export const trace: IStackTrace[] = [ { ordered_globals: ["c"], stdout: "", func_name: "<module>", stack_to_render: [], globals: { c: ["REF" ...

Utilize fixed values in type declaration

Strange Behavior of Typescript: export type MyType = 0 | 1 | 2; The above code snippet functions correctly. However, the following code snippet encounters an issue: export const ONE = 1; export const TWO = 2; export const THREE = 3; export type MyType = O ...

Issues with multiple validators in Angular 8 intricately intertwined

I'm facing an issue with a reactive form control that has multiple validators. Despite defining the validation methods, the form is not being validated as expected. Below is the code snippet illustrating my attempted solutions. Method 1: civilIdNumbe ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Error message 'Module not found' occurring while utilizing dynamic import

After removing CRA and setting up webpack/babel manually, I've encountered issues with dynamic imports. The following code snippet works: import("./" + "CloudIcon" + ".svg") .then(file => { console.log(file); }) However, this snip ...

Utilizing the FormsModule and ReactiveFormsModule within a Component module

I am facing an issue with integrating a reactive form into a generated component called boom-covers. I am utilizing the [formGroup] property as shown below: <form name="boomCovers" method="post" id="bomCovers" (ngSubmit)=&q ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

Exploring the distinction between "() => void" and "() => {}" in programming

Exploring TS types, I defined the following: type type1 = () => {} type type2 = () => void Then, I created variables using these types: const customType1: type1 = () => { } const customType2: type2 = () => { } The issue surfaced as "Type ...

What is the TypeScript definition for the return type of a Reselect function in Redux?

Has anyone been able to specify the return type of the createSelector function in Redux's Reselect library? I didn't find any information on this in the official documentation: https://github.com/reduxjs/reselect#q-are-there-typescript-typings ...

React 18 Fragment expressing concern about an excessive amount of offspring

Recently, I attempted to integrate Storybook into my React application, and it caused a major disruption. Despite restoring from a backup, the absence of the node_modules folder led to issues when trying 'npm install' to recover. Currently, Types ...

Error in Typescript: "Cannot assign to parameter that is of type 'never'"

Here is the code snippet that I am working with: FilesToBlock: []; //defined in this class //within a method of the class this.FilesToBlock = []; this.FilesToBlock.push({file: blockedFile, id: fileID}); However, I'm encountering an issue with fil ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

All constructors at the base level must share a common return type

I am looking to convert my JSX code to TSX. I have a snippet that refactors a method from the react-bootstrap library: import {Panel} from 'react-bootstrap'; class CustomPanel extends Panel { constructor(props, context) { super(props ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...

Problem with Ionic 2 checkboxes in segment controls

I encountered an issue with my screen layout. The problem arises when I select checkboxes from the first segment (Man Segment) and move to the second segment (Woman Segment) to choose other checkboxes. Upon returning to the first segment, all my previous ...