Question3r
Question3r

Reputation: 3742

extending existing validator and only set some options

My database column is of type double precision (from the Postgres docs)

double precision 8 bytes variable-precision, inexact 15 decimal digits precision

Using class-validator I want to make a precision check

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

The IsDecimal decorator might help here, so @IsDecimal({ decimal_digits: '15' }) might do the trick. I would have to use this decorator for multiple fields, is there a way to extend the existing decorator and just pass in the decimal_digits option? I don't think it makes sense to reinvent the wheel. It would be nice if I could inherit the validation but set the precision to less or equal to 15.

Currently I created my own 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 have 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,
        });
    };
}

but I'm not sure if this one is able to handle every case.

Thanks in advance

Upvotes: 0

Views: 4709

Answers (1)

hoangdv
hoangdv

Reputation: 16127

I don't found any example about extending a existed decorator of class-validator, but the IsDecimal just is a normal property decorator, then we can use it as a property decorator.

My idea is creating a "normal" property decorator and call IsDecimal in this decorator with decimal_digits option.

// function as a const
export const IsDoublePrecision = () => { // use decorator factory way
  return (target: object, key: string) => { // return a property decorator function
    IsDecimal({ decimal_digits: '15' })(target, key); // call IsDecimal decorator
  }
}

Usage:

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

Upvotes: 3

Related Questions