UNPKG

validator-experimental-decorators

Version:
65 lines (64 loc) 2.56 kB
"use strict"; //VALIDATOR OF METHOD AND PARAMETER class Validator { //Length Validator Length(minLength, maxLength) { return function (target, propertyKey, descriptor) { const originalData = descriptor.value; descriptor.value = function (...args) { args.forEach((arg) => { if (arg.length < minLength || arg.length > maxLength) { throw new Error("Validation error!"); } }); return originalData.apply(this, args); }; return descriptor; }; } //Negative value validator validateNegativeNumber(target, propertyKey, descriptor) { const originalData = descriptor.value; descriptor.value = function (...args) { 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, propertyKey, descriptor) { const originalData = descriptor.value; descriptor.value = function (...args) { 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, propertyKey, descriptor) { const originalData = descriptor.value; descriptor.value = function (...args) { 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, propertyKey, descriptor) { const originalData = descriptor.value; descriptor.value = function (...args) { 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; } }