我的数据库列的类型为 double precision (来自Postgres docs)
双精度8字节可变精度,不精确的15位十进制数字
使用类验证器进行精确检查
@Isnumber()
/* precision check */
public myValue: number;
IsDecimal
装饰器在这里可能会有所帮助,因此@IsDecimal({ decimal_digits: '15' })
可能会成功。我将不得不将此装饰器用于多个字段,是否可以扩展现有装饰器并仅传递decimal_digits
选项?我认为没有必要重新发明轮子。如果我可以继承验证但将精度设置为小于或等于15 。
当前,我创建了自己的装饰器
@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,});
};
}
但是我不确定这是否能够处理所有情况。
预先感谢