/** * Author: Đào Quốc Huy / huydaoquoc88@gmail.com * Description: word contain [A-Za-z0-9], digit contain [0-9]. Not allow empty, null, undefined input value */ import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; /** * @Example `@IsOTP_I18n("word",4,{message:i18nValidationMessage('validation.INVALID_OTP')})`. * @Param `type`: Default: "digit" ([0-9]). Set "word" for ([A-Za-z0-9]). * @Param `length`: Default: 6. * @Return false if not match any condition, or not set * @Require i18n translate: "validation.INVALID_OTP" */ export function IsOTP_I18n(type: "word" | "digit" = "digit", length: number = 6, validationOptions: ValidationOptions) { return (object: any, propertyName: string) => { registerDecorator({ target: object.constructor, propertyName, options: validationOptions, constraints: [type, length], validator: IsOTP_I18nConstraint, }); }; } @ValidatorConstraint({ name: 'IsOTP_I18n' }) export class IsOTP_I18nConstraint implements ValidatorConstraintInterface { validate(value: any, validationArguments: ValidationArguments) { let validation = false if (typeof value === "string") { // first condition if (validationArguments.constraints[0] === "digit" && value.match(RegExp("(^[0-9]{" + validationArguments.constraints[1] + "}$)"))) { console.log("1") validation = true } else if (validationArguments.constraints[0] === "word" && value.match(RegExp("(^[A-Za-z0-9]{" + validationArguments.constraints[1] + "}$)"))) { console.log("2") validation = true } else { validation = false } } else { validation = false } return validation } defaultMessage(validationArguments?: ValidationArguments): string { return "validation.INVALID_OTP" // return "{"+validationArguments.property + "} " + "response.message.otpFormatIsWrong } }