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