/** * Author: Đào Quốc Huy / huydaoquoc88@gmail.com * Description: Accept number, empty */ import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; /** * @Example `@IsNumber_I18n()`. * @Return true if not set * @Require i18n translate: "validation.INVALID_NUMBER" */ export function IsNumber_I18n(validationOptions?: ValidationOptions) { return (object: any, propertyName: string) => { registerDecorator({ target: object.constructor, propertyName, options: validationOptions, constraints: [], validator: IsNumber_I18nConstraint, }); }; } @ValidatorConstraint({ name: 'IsNumber_I18n' }) export class IsNumber_I18nConstraint implements ValidatorConstraintInterface { validate(value: any, validationArguments?: ValidationArguments) { if (typeof value === "number") { return true } else if (typeof value === "string" && value.match(/ /) !== null) { // dont space return false } else if (typeof value === "string") { let valueParse = parseFloat(value) if ((value !== undefined && value !== null && !isNaN(valueParse)) && typeof valueParse === "number") { return true } else if(typeof value === undefined || value === null){ return true }else { return false } } else { return false } } defaultMessage(validationArguments?: ValidationArguments): string { return "validation.INVALID_NUMBER" } }