【发布时间】:2020-07-27 19:36:45
【问题描述】:
我的数据库列的类型是双精度(来自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,
});
};
}
但我不确定这个是否能够处理所有案件。
提前致谢
【问题讨论】:
标签: typescript typescript-decorator class-validator