Expanding the current validator by configuring specific options

My database column is of type double precision (based on the information provided by the PostgreSQL documentation)

double precision 8 bytes variable-precision, inexact with a precision of up to 15 decimal digits

I am looking to implement a precision check using class-validator.

@IsNumber()
/* precision check */
public myValue: number;

The use of the IsDecimal decorator could be beneficial here; for example,

@IsDecimal({ decimal_digits: '15' })
. Instead of creating a new decorator for each field, is it possible to extend an existing one and specify the decimal_digits option? It would be more efficient to inherit the validation while setting the precision to be less than or equal to 15.

Currently, I have developed my own custom decorator:

@ValidatorConstraint()
class IsDoublePrecisionConstraint implements ValidatorConstraintInterface {
    public validate(value: any): boolean {
        if (typeof value === 'number') {
            if (value % 1 === 0) {
                return true;
            }

            const valueText: string = value.toString();
            const valueSegments: string[] = valueText.split('.');
            const decimalDigits: string = valueSegments[1];

            return decimalDigits.length <= 15;
        }

        return false;
    }

    public defaultMessage(args: ValidationArguments): string {
        return `${args.property} must contain less than or equal to 15 decimal digits.`;
    }
}

export function IsDoublePrecision() {
    return (object: Record<string, any>, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            validator: IsDoublePrecisionConstraint,
        });
    };
}

However, I am uncertain whether this approach covers all scenarios adequately.

Thank you in advance

Answer №1

After searching extensively, I was unable to find any examples of extending an existing decorator from class-validator. However, it became clear that IsDecimal is simply a standard property decorator that can be utilized in this manner.

My concept involves creating a "normal" property decorator and invoking IsDecimal within this decorator while utilizing the decimal_digits option.

// Defining function as a constant
export const IsDoublePrecision = () => { // Utilizing the decorator factory method
  return (target: object, key: string) => { // Return a property decorator function
    IsDecimal({ decimal_digits: '15' })(target, key); // Invoking the IsDecimal decorator
  }
}

Usage:

@IsNumber()
/* Check for precision */
@IsDoublePrecision() 
public myValue: number;

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

Navigating through the child elements of a parent element in Aurelia

I am currently using Aurelia 1 to construct my application. Right now, I am in the process of creating a custom toolbar element known as custom-toolbar.ts. Within this toolbar, there will be an unspecified number of child elements referred to as custom-too ...

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

How can a contextual type be utilized independently of a class instance in TypeScript?

My goal is to find a way to use the this type or something similar outside of a class or interface method in TypeScript, rather than being limited to just within a class or interface. Consider this example: class TypedArray { [index: number]: number; ...

Error Encountered: Unable to locate angular/core module in Angular 2

I have encountered an issue while setting up a new Angular2 app from the quickstart folder on the Angular website. Despite following all suggested solutions, I am still facing errors. After running npm install, everything seems fine as I can see my node_mo ...

The module '#node-web-compat' seems to be missing in the aws-jwt-verify library during testing in Next.js

Problem description When testing a service in an API used in a Next.js app and using Babel Jest for specific test files, I'm encountering an issue regarding locating a module. The error that appears in the terminal is shown below. Cannot fin ...

What is the best way to retrieve all keys from a deeply nested object using recursion

type NestedObject = { amount: number, error: string | null, data: { rows: [], messages: { goodNews: string | null, badNews: string | null } } } //attempting to recursively retrieve all keys type AllKeys<T, K extends keyof T> = T e ...

When it comes to TypeScript, an interface is not just a type definition; it is also a value that can

Can someone help me with this code snippet? export interface Chapter { title: string, path: string } export type TableOfContents: Chapter[] I'm encountering the following error message: [ts] 'Chapter' only refers to a type, but ...

Having trouble typing computed values in Vue Composition API with TypeScript?

I'm attempting to obtain a computed value using the composition API in vue, and here is the code I am working with: setup() { const store = useStore(); const spaUrls = inject<SpaUrls>('spaUrls'); const azureAd = inject<AzureAd ...

What is the best way to ensure that two promises are both resolved before triggering a function from within a promise?

In my code, I have a forEach loop on a matches fetch that looks like this: matches => { matches.forEach(match => { Promise.all([this.teamService.getTeam(match._links.homeTeam.href)]) .then(team => { match. ...

Is there a method or alternative solution for deconstructing TypeScript types/interfaces?

Imagine a scenario where a class has multiple type parameters: class BaseClass<T extends T1, U extends U1, V extends V1, /* etc. */ > Is there a method to consolidate these type arguments in a way that allows for "spreading" or "destructuring," sim ...

Typescript error handling: Handle 404s on all Koa routes

Issue Encountering problems while setting up Auth Controllers Difficulty using Bcrypt and JWT for encryption All POST Calls to Koa resulting in 404 errors Calls to other routes are functioning correctly Potential issue with the scope of the code. impo ...

Steps to create a personalized loading screen using Angular

I am looking to enhance the loading screen for our angular 9 application. Currently, we are utilizing <div [ngClass]="isLoading ? 'loading' : ''> in each component along with the isloading: boolean variable. Whenever an API ...

TS2531: The object's value may potentially be null

Today, I encountered a problem with the following function: uploadPhoto() { var nativeElement: HTMLInputElement = this.fileInput.nativeElement; this.photoService.upload(this.vehicleId, nativeElement.files[0]) .subscribe(x => console.lo ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

Using an object hierarchy in Typescript to create an if statement

Currently, I am attempting to create a logical statement using a hierarchy structure as shown below: if ((config.elementConfig.curve[0].dataset[0].splitBy = 'my discrete var')) {..... However, when implementing this statement, I encounter the er ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

The Carousel Slider seems to encounter issues when trying to implement it with *ngFor in Angular 8

Currently tackling an issue in Angular 8 where my slider functions perfectly with static data. However, upon attempting to loop through some dynamic data, the 'left' and 'right' buttons on the carousel cease to work. The images also fai ...

TypeScript errors undetected by ESlint

I am currently working on a nextJS app with typescript in VSCode. I've noticed that while VSCode accurately displays TS errors when I open a file with an error, the eslint doesn't seem to do the same. For instance, here are the errors shown in m ...

Implementing GetServerSideProps with Next-Auth: Error message - Trying to destructure property 'nextauth' from 'req.query' which is undefined

I encountered an issue while using the getServerSideProps function in Next.js with Next-Auth. The error I received was a TypeError: TypeError: Cannot destructure property 'nextauth' of 'req.query' as it is undefined. Upon checking with ...

Whenever I make a POST request to the API in Ionic 2, I encounter a "Connection refused (x192)" error

I have been struggling with an error in my code for the past two days and I can't seem to find a solution. Can someone please help me with this? The error message is as follows: [Error] WebSocket network error: The operation couldn’t be complet ...