扩展现有的验证器,仅设置一些选项

我的数据库列的类型为 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,});
    };
}

但是我不确定这是否能够处理所有情况。

预先感谢

lulou215 回答:扩展现有的验证器,仅设置一些选项

我没有找到有关扩展class-validator的现有装饰器的任何示例,但是IsDecimal只是一个普通的属性装饰器,因此我们可以将其用作属性装饰器。

我的想法是创建一个“常规”属性装饰器,并使用IsDecimal选项在此装饰器中调用decimal_digits

// 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
  }
}

用法:

@IsNumber()
/* precision check */
@IsDoublePrecision()
public myValue: number;
本文链接:https://www.f2er.com/2441039.html

大家都在问