UNPKG

validator-experimental-decorators

Version:
97 lines (80 loc) 2.6 kB
//VALIDATOR OF METHOD AND PARAMETER export default class Validator { //Length Validator Length(minLength: number, maxLength: number) { return function ( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { const originalData = descriptor.value; descriptor.value = function (...args: any[]) { args.forEach((arg: string) => { if (arg.length < minLength || arg.length > maxLength) { throw new Error("Validation error!"); } }); return originalData.apply(this, args); }; return descriptor; }; } //Negative value validator validateNegativeNumber( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { const originalData = descriptor.value; descriptor.value = function (...args: any[]) { const parameterValue = args[0]; if (typeof parameterValue !== "number" || parameterValue >= 0) { throw new Error("Invalid parameter value. Expected a negative number"); } return originalData.apply(this, args); }; } validatePositiveNumber( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { const originalData = descriptor.value; descriptor.value = function (...args: any[]) { const parameterValue = args[0]; if (typeof parameterValue !== "number" || parameterValue <= 0) { throw new Error("Invalid parameter value. Expected a positive number"); } return originalData.apply(this, args); }; } isEmail(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalData = descriptor.value; descriptor.value = function (...args: any[]) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const userInput = args[0]; if (!emailRegex.test(userInput)) { throw new Error("invalid mail"); } return originalData.apply(this, args); }; return descriptor; } isValidPassword( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { const originalData = descriptor.value; descriptor.value = function (...args: any[]) { const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/; const userInput = args[0]; if (passwordRegex.test(userInput)) { throw new Error("Invalid password"); } return originalData.apply(this, args); }; return descriptor; } }