From 54a9af539eb6be2574b6dc75fd6683bfd9c9a5f1 Mon Sep 17 00:00:00 2001 From: Gabriel Logan Date: Wed, 2 Oct 2024 22:49:18 -0300 Subject: [PATCH] improving code formatting with sonar lint and adding more tests --- index.ts | 1 - package.json | 2 +- src/cnpjValidator.ts | 6 +- src/cpfValidator.ts | 6 +- src/isDate.ts | 11 +- src/isDecimal.ts | 82 +++++++------ src/isEmail.ts | 33 +++--- src/isTime.ts | 2 +- src/isValidTxt/index.ts | 8 +- src/passwordStrengthTester.ts | 116 +++++++++++++++---- src/validateBRPhoneNumber.ts | 6 +- src/validateEmail.ts | 119 ++++++++++--------- src/validateName.ts | 129 ++++++++++----------- src/validatePassportNumber.ts | 20 ++-- src/validatePassword.ts | 150 +++++++++++++++--------- src/validatePhoneNumber.ts | 6 +- src/validateSurname.ts | 125 ++++++++++---------- src/validateTextarea.ts | 8 +- src/validateUSPhoneNumber.ts | 6 +- src/validateUsername.ts | 177 ++++++++++++++++++----------- tests/src/isAscii.test.ts | 4 + tests/src/isDecimal.test.ts | 16 ++- tests/src/isEmail.test.ts | 8 ++ tests/src/validatePassword.test.ts | 28 +++++ tests/testerGeral.test.ts | 1 - 25 files changed, 641 insertions(+), 429 deletions(-) diff --git a/index.ts b/index.ts index 5d33d8a..013762b 100644 --- a/index.ts +++ b/index.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import cpfIsValid from "./src/cpfValidator"; import cnpjIsValid from "./src/cnpjValidator"; import getOnlyEmail from "./src/getOnlyEmail"; diff --git a/package.json b/package.json index 131c0b8..2f3f6d5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "multiform-validator", - "version": "2.2.4", + "version": "2.2.5", "description": "Javascript library made to validate, several form fields, such as: email, images, phone, password, cpf etc.", "main": "./dist/cjs/index.cjs", "module": "./dist/esm/index.mjs", diff --git a/src/cnpjValidator.ts b/src/cnpjValidator.ts index d397e70..52c06f2 100644 --- a/src/cnpjValidator.ts +++ b/src/cnpjValidator.ts @@ -59,8 +59,8 @@ function cnpjIsValid( // caso contrario retorna um ERRO if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("Must be an Array"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); @@ -71,7 +71,7 @@ function cnpjIsValid( // Função interna para obter a mensagem de erro function getErrorMessage(index: number): string { const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; + return errorMessage ?? defaultErrorMsg[index]; } if (!cnpj) { diff --git a/src/cpfValidator.ts b/src/cpfValidator.ts index 353ab43..918634e 100644 --- a/src/cpfValidator.ts +++ b/src/cpfValidator.ts @@ -31,8 +31,8 @@ function cpfIsValid( if (errorMsg) { if (!Array.isArray(errorMsg)) throw new TypeError("Must be an Array"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); @@ -42,7 +42,7 @@ function cpfIsValid( function getErrorMessage(index: number): string { const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; + return errorMessage ?? defaultErrorMsg[index]; } if (!cpf) { diff --git a/src/isDate.ts b/src/isDate.ts index e71701b..22bddde 100644 --- a/src/isDate.ts +++ b/src/isDate.ts @@ -24,9 +24,14 @@ function isDate(value: string): boolean { return false; } // Check if the date string is in a valid format (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY', 'MMMM D, YYYY') - const dateStringRegex: RegExp = - /^(?:\d{4}[-/]\d{2}[-/]\d{2}|\d{2}[-/]\d{2}[-/]\d{4}|[A-Za-z]+\s\d{1,2}, \d{4})$/; - if (!dateStringRegex.test(value)) { + const dateStringRegex1: RegExp = /^\d{4}[-/]\d{2}[-/]\d{2}$/; // 'YYYY-MM-DD' or 'YYYY/MM/DD' + const dateStringRegex2: RegExp = /^\d{2}[-/]\d{2}[-/]\d{4}$/; // 'MM-DD-YYYY' or 'MM/DD/YYYY' + const dateStringRegex3: RegExp = /^[A-Za-z]+\s\d{1,2}, \d{4}$/; // 'MMMM D, YYYY' + if ( + !dateStringRegex1.test(value) && + !dateStringRegex2.test(value) && + !dateStringRegex3.test(value) + ) { return false; } // Additional checks for the month and day values diff --git a/src/isDecimal.ts b/src/isDecimal.ts index 3712ee2..d0bb323 100644 --- a/src/isDecimal.ts +++ b/src/isDecimal.ts @@ -12,56 +12,72 @@ */ function isDecimal(value: string | number): boolean { let getValued: string | number = value; - if (typeof getValued === "number" && Number.isNaN(getValued)) { - throw new TypeError("Input value must not be NaN."); - } - - if (typeof getValued === "number" && !isFinite(getValued)) { - throw new TypeError("Input value must not be Infinity, -Infinity or NaN."); - } + validateInput(getValued); - if (typeof getValued !== "string") { - if (typeof getValued === "number") { - if (Number.isInteger(getValued)) { - return false; - } - getValued = getValued.toString(); - } else { - throw new TypeError("Input value must be a string or a number."); + if (typeof getValued === "number") { + if (Number.isInteger(getValued)) { + return false; } + getValued = getValued.toString(); } + if (getValued.trim().length === 0) { throw new Error("Input value must not be an empty string."); } - const integerRegex: RegExp = /^\d+$/; - if (integerRegex.test(getValued)) { + if (isInteger(getValued)) { return false; } - // Regular expression to validate decimal numbers - const decimalRegex: RegExp = /^[-+]?(?:\d+(?:[,.]\d*)?|\d*[,.]\d+)$/; - if (!decimalRegex.test(getValued)) { + if (!isValidDecimal(getValued)) { return false; } - // Check for multiple decimal separators - const decimalSeparator: Separators = getValued.includes(".") ? "." : ","; - const otherSeparator: Separators = decimalSeparator === "." ? "," : "."; - if ( - getValued.includes(decimalSeparator) && - getValued.includes(otherSeparator) - ) { + + if (hasMultipleSeparators(getValued)) { return false; } - // Additional checks for negative sign - if (getValued.startsWith("-")) { - // Ensure the negative sign is only at the beginning and not elsewhere - if (getValued.lastIndexOf("-") > 0) { - return false; - } + + if (hasInvalidNegativeSign(getValued)) { + return false; } + return true; } + +function validateInput(value: string | number): void { + if (typeof value === "number" && Number.isNaN(value)) { + throw new TypeError("Input value must not be NaN."); + } + + if (typeof value === "number" && !isFinite(value)) { + throw new TypeError("Input value must not be Infinity, -Infinity or NaN."); + } + + if (typeof value !== "string" && typeof value !== "number") { + throw new TypeError("Input value must be a string or a number."); + } +} + +function isInteger(value: string): boolean { + const integerRegex: RegExp = /^\d+$/; + return integerRegex.test(value); +} + +function isValidDecimal(value: string): boolean { + const decimalRegex: RegExp = /^[-+]?(?:\d+(?:[,.]\d*)?|\d*[,.]\d+)$/; + return decimalRegex.test(value); +} + +function hasMultipleSeparators(value: string): boolean { + const decimalSeparator: Separators = value.includes(".") ? "." : ","; + const otherSeparator: Separators = decimalSeparator === "." ? "," : "."; + return value.includes(decimalSeparator) && value.includes(otherSeparator); +} + +function hasInvalidNegativeSign(value: string): boolean { + return value.startsWith("-") && value.lastIndexOf("-") > 0; +} + export default isDecimal; type Separators = "." | ","; diff --git a/src/isEmail.ts b/src/isEmail.ts index 278b62c..042c8e0 100644 --- a/src/isEmail.ts +++ b/src/isEmail.ts @@ -35,35 +35,38 @@ function isEmail(email: string): boolean { // Check if email starts with a special character const startsWithSpecialChar: RegExp = /^[^a-zA-Z0-9]/; - if (startsWithSpecialChar.test(email)) return false; + if (startsWithSpecialChar.test(email)) { + return false; + } const regex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; - if (Number(email[0])) return false; + if (Number(email[0])) { + return false; + } - if (!regex.test(email)) return false; + if (!regex.test(email)) { + return false; + } const antesDoArroba: number = email.indexOf("@"); const depoisDoArroba: number = email.indexOf("@") + 1; - const depoisDoUltimoPonto: number = email.lastIndexOf("."); - - if (Number(email[depoisDoArroba])) return false; - - if (Number(email[depoisDoUltimoPonto])) return false; - - if (email.substring(0, antesDoArroba).includes("..")) return false; + if (Number(email[depoisDoArroba])) { + return false; + } - if (email.substring(0, antesDoArroba).endsWith(".")) return false; + if (email.substring(0, antesDoArroba).includes("..")) { + return false; + } - const parts: string[] = email.split("."); - if (parts.length > 2 && parts[parts.length - 2] === parts[parts.length - 3]) { + if (email.substring(0, antesDoArroba).endsWith(".")) { return false; } - // Check if there is more than one @ - if (email.split("@").length - 1 > 1) { + const parts: string[] = email.split("."); + if (parts.length > 2 && parts[parts.length - 2] === parts[parts.length - 3]) { return false; } diff --git a/src/isTime.ts b/src/isTime.ts index 7e35689..35c7285 100644 --- a/src/isTime.ts +++ b/src/isTime.ts @@ -16,7 +16,7 @@ function isTime(time: string): boolean { } // Regular expression to validate time in the format "hh:mm" or "hh:mm AM/PM" or "hh:mm:ss" or "hh:mm:ss AM/PM" const timeRegex: RegExp = - /^(?:2[0-3]|1\d|0?[0-9]):[0-5]\d(?::[0-5]\d)?(?: [APap][Mm])?$/; + /^(?:2[0-3]|1\d|0?\d):[0-5]\d(?::[0-5]\d)?(?: [APap][Mm])?$/; return timeRegex.test(time); } diff --git a/src/isValidTxt/index.ts b/src/isValidTxt/index.ts index fbd608c..f4682b3 100644 --- a/src/isValidTxt/index.ts +++ b/src/isValidTxt/index.ts @@ -7,11 +7,11 @@ export default function isValidTxt(fileBuffer: Buffer): boolean { if (fileBuffer.length === 0) { return false; } - for (let i: number = 0; i < fileBuffer.length; i++) { + for (const element of fileBuffer) { if ( - (fileBuffer[i] < 0x20 || fileBuffer[i] > 0x7e) && - fileBuffer[i] !== 0x0a && - fileBuffer[i] !== 0x0d + (element < 0x20 || element > 0x7e) && + element !== 0x0a && + element !== 0x0d ) { return false; } diff --git a/src/passwordStrengthTester.ts b/src/passwordStrengthTester.ts index 9d7394e..2c8393d 100644 --- a/src/passwordStrengthTester.ts +++ b/src/passwordStrengthTester.ts @@ -23,54 +23,120 @@ function passwordStrengthTester(password: string): string { throw new TypeError("The input should be a string."); } const passwordLength: number = password.length; - let strengthType: string = "unknow"; + let strengthType: string; + switch (true) { - case passwordLength <= 5 && /^\d+$/.test(password): + case isVeryWeak(password, passwordLength) || commonPassword(password): strengthType = "veryWeak"; break; - case (passwordLength <= 5 && /^[a-zA-Z0-9]+$/.test(password)) || - (passwordLength >= 6 && - /^[a-zA-Z0-9]+$/.test(password) && - passwordLength <= 7) || - (passwordLength < 10 && /(.)\1{3,}/.test(password)) || - (passwordLength >= 5 && passwordLength <= 8 && /^\d+$/.test(password)): + case isWeak(password, passwordLength): strengthType = "weak"; break; - case /(.)\1{5,}/.test(password) && passwordLength > 10: + case isRegular(password, passwordLength): strengthType = "regular"; break; - case passwordLength > 16 || - (password.length >= 8 && - /[A-Z]/.test(password) && - /[a-z]/.test(password) && - /[0-9]/.test(password) && - /[\W_]/.test(password)): + case isVeryStrong(password, passwordLength): strengthType = "veryStrong"; break; - case (passwordLength >= 13 && passwordLength <= 16) || - (password.length >= 8 && - /[A-Z]/.test(password) && - /[a-z]/.test(password) && - /[0-9]/.test(password)): + case isStrong(password, passwordLength): strengthType = "strong"; break; - case (passwordLength >= 9 && passwordLength <= 12) || - (password.length >= 6 && - password.length <= 8 && - /[0-9]/.test(password) && - /[a-zA-Z]/.test(password)): + case isRegular2(password, passwordLength): strengthType = "regular"; break; default: + strengthType = "not classified"; break; } + return strengthType; } +function isVeryWeak(password: string, passwordLength: number): boolean { + return passwordLength <= 5 && /^\d+$/.test(password); +} + +function isWeak(password: string, passwordLength: number): boolean { + return ( + (passwordLength <= 5 && /^[a-zA-Z0-9]+$/.test(password)) || + (passwordLength >= 6 && + /^[a-zA-Z0-9]+$/.test(password) && + passwordLength <= 7) || + (passwordLength < 10 && /(.)\1{3,}/.test(password)) || + (passwordLength >= 5 && passwordLength <= 8 && /^\d+$/.test(password)) + ); +} + +function isRegular(password: string, passwordLength: number): boolean { + return /(.)\1{5,}/.test(password) && passwordLength > 10; +} + +function isVeryStrong(password: string, passwordLength: number): boolean { + return ( + passwordLength > 16 || + (password.length >= 8 && + /[A-Z]/.test(password) && + /[a-z]/.test(password) && + /\d/.test(password) && + /[\W_]/.test(password)) + ); +} + +function isRegular2(password: string, passwordLength: number): boolean { + return ( + (passwordLength >= 9 && passwordLength <= 12) || + (password.length >= 6 && + password.length <= 8 && + /\d/.test(password) && + /[a-zA-Z]/.test(password)) + ); +} + +function isStrong(password: string, passwordLength: number): boolean { + return ( + (passwordLength >= 13 && passwordLength <= 16) || + (password.length >= 8 && + /[A-Z]/.test(password) && + /[a-z]/.test(password) && + /\d/.test(password)) + ); +} + +function commonPassword(password: string): boolean { + const commonPasswords: string[] = [ + "123", + "1234", + "12345", + "123456", + "1234567", + "12345678", + "123456789", + "password", + "password", + "password!", + "password!1", + "admin", + "admin!", + "Admin", + "Admin!", + "admin123", + "P@ssw0rd", + "Password", + "password123", + "password123!", + "Qwerty", + "Qwerty!", + "Qwerty123", + "Qwerty123!", + ]; + + return commonPasswords.includes(password); +} + export default passwordStrengthTester; diff --git a/src/validateBRPhoneNumber.ts b/src/validateBRPhoneNumber.ts index 979fbc0..8bafa64 100644 --- a/src/validateBRPhoneNumber.ts +++ b/src/validateBRPhoneNumber.ts @@ -27,8 +27,8 @@ function validateBRPhoneNumber( // Check to see if the passed error messages are valid; otherwise, return an error if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("errorMsg must be an Array"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); @@ -39,7 +39,7 @@ function validateBRPhoneNumber( // Internal function to get the error message function getErrorMessage(index: number): string { const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; + return errorMessage ?? defaultErrorMsg[index]; } if (!phoneNumber) { diff --git a/src/validateEmail.ts b/src/validateEmail.ts index 9aced8b..7102332 100644 --- a/src/validateEmail.ts +++ b/src/validateEmail.ts @@ -83,89 +83,96 @@ function validateEmail( throw new TypeError("The input should be a string."); } - // Expressão regular para verificar se o e-mail termina com um dos domínios válidos - let regex: RegExp = /(?:)/; // Inicialização com uma expressão regular vazia + const regex: RegExp | null = getDomainRegex(validDomains ?? false); - if (Array.isArray(validDomains) && validDomains.length > 0) { - const validDomainsCustom: string[] = validDomains.map((domain: string) => - domain.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), - ); - regex = new RegExp(`${validDomainsCustom.join("|")}$`, "i"); - } else if (validDomains) { - regex = new RegExp(`${validDomainsDefault.join("|")}$`, "i"); - } + validateErrorMsg(errorMsg); - // Check para saber se as mensagens que sao passadas sao validas - // caso contrario retorna um ERRO - if (errorMsg) { - if (!Array.isArray(errorMsg)) - throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { - throw new TypeError( - "All values within the array must be strings or null/undefined.", - ); - } - } - } - - if (maxLength || maxLength === 0) { - if (maxLength < 1 || typeof maxLength !== "number") { - throw new Error("maxLength must be a number and cannot be less than 1"); - } - } - - const maxEmailLength: number = maxLength || 400; - - // Função interna para obter a mensagem de erro - function getErrorMessage(index: number): string { - const errorMessage: string | null = errorMsg - ? errorMsg[index] - : defaultErrorMsg[index]; - if (errorMessage === "Email too big, try again") { - return `Email cannot be greater than ${maxEmailLength} characters`; - } - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; - } + const maxEmailLength: number = validateMaxLength(maxLength); if (!email) { return { isValid: false, - errorMsg: getErrorMessage(0), + errorMsg: getErrorMessage(0, errorMsg, maxEmailLength), }; } - // Check domain only if regex is defined (validDomains is true or validDomains is an array) - if (!regex.test(email)) { + if (regex && !regex.test(email)) { return { isValid: false, - errorMsg: getErrorMessage(4), + errorMsg: getErrorMessage(4, errorMsg, maxEmailLength), }; } if (!isEmail(email)) { return { isValid: false, - errorMsg: getErrorMessage(1), + errorMsg: getErrorMessage(1, errorMsg, maxEmailLength), }; } if (email.length > maxEmailLength) { return { isValid: false, - errorMsg: getErrorMessage(2), + errorMsg: getErrorMessage(2, errorMsg, maxEmailLength), }; } - // If country is provided, check if the email ends with the country code - if (country) { - if (!email.endsWith(`.${country}`)) { - return { - isValid: false, - errorMsg: getErrorMessage(3), - }; - } + if (country && !email.endsWith(`.${country}`)) { + return { + isValid: false, + errorMsg: getErrorMessage(3, errorMsg, maxEmailLength), + }; } return { isValid: true, errorMsg: null, }; } + +function getDomainRegex(validDomains: boolean | string[]): RegExp | null { + if (Array.isArray(validDomains) && validDomains.length > 0) { + const validDomainsCustom: string[] = validDomains.map((domain: string) => + domain.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), + ); + return new RegExp(`${validDomainsCustom.join("|")}$`, "i"); + } + if (validDomains) { + return new RegExp(`${validDomainsDefault.join("|")}$`, "i"); + } + return null; +} + +function validateErrorMsg(errorMsg: (string | null)[] | undefined): void { + if (errorMsg) { + if (!Array.isArray(errorMsg)) + throw new Error("errorMsg must be an Array or null"); + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { + throw new TypeError( + "All values within the array must be strings or null/undefined.", + ); + } + } + } +} + +function validateMaxLength(maxLength: number | undefined): number { + if (maxLength || maxLength === 0) { + if (maxLength < 1 || typeof maxLength !== "number") { + throw new Error("maxLength must be a number and cannot be less than 1"); + } + } + return maxLength ?? 400; +} + +function getErrorMessage( + index: number, + errorMsg: (string | null)[] | undefined, + maxEmailLength: number, +): string { + const errorMessage: string | null = errorMsg + ? errorMsg[index] + : defaultErrorMsg[index]; + if (errorMessage === "Email too big, try again") { + return `Email cannot be greater than ${maxEmailLength} characters`; + } + return errorMessage ?? defaultErrorMsg[index]; +} export default validateEmail; diff --git a/src/validateName.ts b/src/validateName.ts index a0b0ee1..0871bfd 100644 --- a/src/validateName.ts +++ b/src/validateName.ts @@ -49,98 +49,87 @@ function validateName( if (typeof name !== "string") { throw new TypeError("The input should be a string."); } - // Check para saber se as mensagens que sao passadas sao validas - // caso contrario retorna um ERRO + + validateErrorMsg(errorMsg); + + const minNameLength: number = minLength ?? 1; + const maxNameLength: number = maxLength ?? 20; + + validateLengths(minNameLength, maxNameLength); + + const getErrorMessage: (index: number) => string = + createErrorMessageGetter(errorMsg); + + if (!name) { + return createInvalidResult(getErrorMessage(0)); + } + if (name.length > maxNameLength) { + return createInvalidResult(getErrorMessage(4)); + } + if (name.length < minNameLength) { + return createInvalidResult(getErrorMessage(3)); + } + if (RegExp(/\d/).exec(name)) { + return createInvalidResult(getErrorMessage(1)); + } + if (RegExp(/[^\w\s]/).exec(name)) { + return createInvalidResult(getErrorMessage(2)); + } + if (new Set(name).size === 1) { + return createInvalidResult(getErrorMessage(3)); + } + if (/(\w)\1\1/.test(name)) { + return createInvalidResult(getErrorMessage(3)); + } + + return { + isValid: true, + errorMsg: null, + }; +} + +function validateErrorMsg(errorMsg: (string | null)[] | undefined): void { if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); } } } +} - // Função interna para obter a mensagem de erro - function getErrorMessage(index: number): string { - const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; - } - - const minNameLength: number = minLength || 1; - const maxNameLength: number = maxLength || 20; - +function validateLengths(minLength: number, maxLength: number): void { if ( - maxNameLength < 1 || - minNameLength < 1 || - typeof minNameLength !== "number" || - typeof maxNameLength !== "number" + maxLength < 1 || + minLength < 1 || + typeof minLength !== "number" || + typeof maxLength !== "number" ) { throw new Error( "maxLength or minLength must be a number and cannot be less than 1", ); } - if (minNameLength > maxNameLength) { + if (minLength > maxLength) { throw new Error("minLength cannot be greater than maxLength"); } +} - if (!name) { - return { - isValid: false, - errorMsg: getErrorMessage(0), - }; - } - if (name.length > maxNameLength) { - return { - isValid: false, - errorMsg: getErrorMessage(4), - }; - } - - if (name.length < minNameLength) { - return { - isValid: false, - errorMsg: getErrorMessage(3), - }; - } - - if (name.match(/\d/)) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } - - if (name.match(/[^\w\s]/)) { - return { - isValid: false, - errorMsg: getErrorMessage(2), - }; - } - - // Check if all characters in the name are repeated - if (new Set(name).size === 1) { - return { - isValid: false, - errorMsg: getErrorMessage(3), // Assuming 'Name is not allowed.' refers to all characters being repeated. - }; - } - - // Check if the name contains at least 3 consecutive characters that are the same - const consecutiveCharsRegex: RegExp = /(\w)\1\1/; - if (consecutiveCharsRegex.test(name)) { - return { - isValid: false, - errorMsg: getErrorMessage(3), // You can set the appropriate error message for this case. - }; - } +function createErrorMessageGetter(errorMsg: (string | null)[] | undefined) { + return function getErrorMessage(index: number): string { + const errorMessage: string | null = errorMsg ? errorMsg[index] : null; + return errorMessage ?? defaultErrorMsg[index]; + }; +} +function createInvalidResult(errorMsg: string): ValidateFunctions { return { - isValid: true, - errorMsg: null, + isValid: false, + errorMsg, }; } diff --git a/src/validatePassportNumber.ts b/src/validatePassportNumber.ts index e78ae98..4268e7b 100644 --- a/src/validatePassportNumber.ts +++ b/src/validatePassportNumber.ts @@ -20,16 +20,16 @@ function validatePassportNumber( country: string; regex: RegExp; }[] = [ - { country: "United States", regex: /^[0-9]{9}$/ }, - { country: "United Kingdom", regex: /^[A-Z]{2}[0-9]{6}$/ }, - { country: "Germany", regex: /^[A-Z]{2}[0-9]{8}$/ }, - { country: "Canada", regex: /^[A-Z][0-9]{7}$/ }, - { country: "Australia", regex: /^[A-Z][0-9]{7}$/ }, - { country: "Brazil", regex: /^[0-9]{9}$/ }, - { country: "France", regex: /^[A-Z]{2}[0-9]{7}$/ }, - { country: "Italy", regex: /^[A-Z][0-9]{7}$/ }, - { country: "India", regex: /^[A-Z][0-9]{7}$/ }, - { country: "China", regex: /^[A-Z][0-9]{8}$/ }, + { country: "United States", regex: /^\d{9}$/ }, + { country: "United Kingdom", regex: /^[A-Z]{2}\d{6}$/ }, + { country: "Germany", regex: /^[A-Z]{2}\d{8}$/ }, + { country: "Canada", regex: /^[A-Z]\d{7}$/ }, + { country: "Australia", regex: /^[A-Z]\d{7}$/ }, + { country: "Brazil", regex: /^\d{9}$/ }, + { country: "France", regex: /^[A-Z]{2}\d{7}$/ }, + { country: "Italy", regex: /^[A-Z]\d{7}$/ }, + { country: "India", regex: /^[A-Z]\d{7}$/ }, + { country: "China", regex: /^[A-Z]\d{8}$/ }, ]; // Verificar o formato do passaporte antes de verificar o país for (const format of passportFormats) { diff --git a/src/validatePassword.ts b/src/validatePassword.ts index e042073..8b4a70a 100644 --- a/src/validatePassword.ts +++ b/src/validatePassword.ts @@ -83,40 +83,63 @@ function validatePassword( if (typeof password !== "string") { throw new TypeError("The input should be a string."); } - // Check para saber se as mensagens que sao passadas sao validas - // caso contrario retorna um ERRO + + validateErrorMsg(errorMsg); + + const minLenthPassword: number = minLength ?? 1; + const maxLenthPassword: number = maxLength ?? Infinity; + + validateLengthParams(minLenthPassword, maxLenthPassword); + + const errorMessage: string | null = validatePasswordLength( + password, + minLenthPassword, + maxLenthPassword, + errorMsg, + ); + if (errorMessage) { + return { + isValid: false, + errorMsg: errorMessage, + }; + } + + const optionErrorMessage: string | null = validatePasswordOptions( + password, + options, + errorMsg, + ); + if (optionErrorMessage) { + return { + isValid: false, + errorMsg: optionErrorMessage, + }; + } + + return { + isValid: true, + errorMsg: null, + }; +} + +function validateErrorMsg(errorMsg: (string | null)[] | undefined) { if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); } } } +} - const minLenthPassword: number = minLength || 1; - const maxLenthPassword: number = maxLength || Infinity; - - // Função interna para obter a mensagem de erro - function getErrorMessage(index: number): string { - const errorMessage: string | null = errorMsg - ? errorMsg[index] - : defaultErrorMsg[index]; - if ( - errorMessage === "This password is too long" || - errorMessage === "password too short" - ) { - if (maxLenthPassword === Infinity) { - return `Password must be greater than ${minLenthPassword} characters`; - } - return `Password must be between ${minLenthPassword} and ${maxLenthPassword} characters`; - } - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; - } - +function validateLengthParams( + minLenthPassword: number, + maxLenthPassword: number, +) { if ( typeof minLenthPassword !== "number" || typeof maxLenthPassword !== "number" @@ -126,52 +149,67 @@ function validatePassword( if (minLenthPassword > maxLenthPassword) { throw new Error("the minimum size cannot be larger than the maximum"); - } // Verifica se o min é maior que o max + } if (minLenthPassword < 1 || maxLenthPassword < 1) { throw new Error("No size can be smaller than 1"); - } // Nenhum dos dois pode ser menor que 1 + } +} +function validatePasswordLength( + password: string, + minLenthPassword: number, + maxLenthPassword: number, + errorMsg: (string | null)[] | undefined, +): string | null { if (password.length > maxLenthPassword) { - return { - isValid: false, - errorMsg: getErrorMessage(0), - }; - } // Tamanho da palavra não pode ser maior que o tamanho máximo + return getErrorMessage(0, minLenthPassword, maxLenthPassword, errorMsg); + } if (password.length < minLenthPassword) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } // Tamanho n pode ser menor q o min + return getErrorMessage(1, minLenthPassword, maxLenthPassword, errorMsg); + } + return null; +} + +function validatePasswordOptions( + password: string, + options: Options | undefined, + errorMsg: (string | null)[] | undefined, +): string | null { if (options?.requireUppercase && !/[A-Z]/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(2), // Requer pelo menos uma letra maiuscula - }; + return getErrorMessage(2, 0, 0, errorMsg); } if (options?.requireSpecialChar && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(3), // Requer pelo menos uma especial caracter - }; + return getErrorMessage(3, 0, 0, errorMsg); } if (options?.requireNumber && !/\d/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(4), // Requer pelo menos um numero - }; + return getErrorMessage(4, 0, 0, errorMsg); } if (options?.requireString && !/[a-zA-Z]/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(5), // Requer pelo menos uma letra - }; + return getErrorMessage(5, 0, 0, errorMsg); } - return { - isValid: true, - errorMsg: null, - }; + return null; +} + +function getErrorMessage( + index: number, + minLenthPassword: number, + maxLenthPassword: number, + errorMsg: (string | null)[] | undefined, +): string { + const errorMessage: string | null = errorMsg + ? errorMsg[index] + : defaultErrorMsg[index]; + if ( + errorMessage === "This password is too long" || + errorMessage === "password too short" + ) { + if (maxLenthPassword === Infinity) { + return `Password must be greater than ${minLenthPassword} characters`; + } + return `Password must be between ${minLenthPassword} and ${maxLenthPassword} characters`; + } + return errorMessage ?? defaultErrorMsg[index]; } export default validatePassword; diff --git a/src/validatePhoneNumber.ts b/src/validatePhoneNumber.ts index 4043302..b3b3c8f 100644 --- a/src/validatePhoneNumber.ts +++ b/src/validatePhoneNumber.ts @@ -24,8 +24,8 @@ function validatePhoneNumber( if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); @@ -36,7 +36,7 @@ function validatePhoneNumber( // Internal function to get the error message function getErrorMessage(index: number): string { const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; + return errorMessage ?? defaultErrorMsg[index]; } if (!phoneNumber) { diff --git a/src/validateSurname.ts b/src/validateSurname.ts index c80c481..69ccbd2 100644 --- a/src/validateSurname.ts +++ b/src/validateSurname.ts @@ -50,31 +50,62 @@ function validateSurname( throw new TypeError("The input should be a string."); } - // Check para saber se as mensagens que sao passadas sao validas - // caso contrario retorna um ERRO + validateErrorMsg(errorMsg); + const minNameLength: number = minLength ?? 1; + const maxNameLength: number = maxLength ?? 25; + + validateLengths(minNameLength, maxNameLength); + + if (!surname) { + return createErrorResponse(0, errorMsg); + } + + if (surname.length > maxNameLength) { + return createErrorResponse(4, errorMsg); + } + if (surname.length < minNameLength) { + return createErrorResponse(3, errorMsg); + } + + if (RegExp(/\d/).exec(surname)) { + return createErrorResponse(1, errorMsg); + } + + if (RegExp(/[^\w\s]/).exec(surname)) { + return createErrorResponse(2, errorMsg); + } + + if (new Set(surname).size === 1) { + return createErrorResponse(3, errorMsg); + } + + if (/(\w)\1\1/.test(surname)) { + return createErrorResponse(3, errorMsg); + } + + return { + isValid: true, + errorMsg: null, + }; +} + +function validateErrorMsg(errorMsg: (string | null)[] | undefined): void { if (errorMsg) { if (!Array.isArray(errorMsg)) { throw new Error("errorMsg must be an Array or null"); } - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); } } } +} - // Função interna para obter a mensagem de erro - function getErrorMessage(index: number): string { - const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; - } - - const minNameLength: number = minLength || 1; - const maxNameLength: number = maxLength || 25; - +function validateLengths(minNameLength: number, maxNameLength: number): void { if ( maxNameLength < 1 || minNameLength < 1 || @@ -89,61 +120,23 @@ function validateSurname( if (minNameLength > maxNameLength) { throw new Error("minLength cannot be greater than maxLength"); } +} - if (!surname) { - return { - isValid: false, - errorMsg: getErrorMessage(0), - }; - } - - if (surname.length > maxNameLength) { - return { - isValid: false, - errorMsg: getErrorMessage(4), - }; - } - if (surname.length < minNameLength) { - return { - isValid: false, - errorMsg: getErrorMessage(3), - }; - } - - if (surname.match(/\d/)) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } - - if (surname.match(/[^\w\s]/)) { - return { - isValid: false, - errorMsg: getErrorMessage(2), - }; - } - - // Check if all characters in the surname are repeated - if (new Set(surname).size === 1) { - return { - isValid: false, - errorMsg: getErrorMessage(3), // Assuming 'Surname is not allowed.' refers to all characters being repeated. - }; - } - - // Check if the surname contains at least 3 consecutive characters that are the same - const consecutiveCharsRegex: RegExp = /(\w)\1\1/; - if (consecutiveCharsRegex.test(surname)) { - return { - isValid: false, - errorMsg: getErrorMessage(3), // You can set the appropriate error message for this case. - }; - } - +function createErrorResponse( + index: number, + errorMsg: (string | null)[] | undefined, +): ValidateFunctions { return { - isValid: true, - errorMsg: null, + isValid: false, + errorMsg: getErrorMessage(index, errorMsg), }; } + +function getErrorMessage( + index: number, + errorMsg: (string | null)[] | undefined, +): string { + const errorMessage: string | null = errorMsg ? errorMsg[index] : null; + return errorMessage ?? defaultErrorMsg[index]; +} export default validateSurname; diff --git a/src/validateTextarea.ts b/src/validateTextarea.ts index 19a7c93..4c79777 100644 --- a/src/validateTextarea.ts +++ b/src/validateTextarea.ts @@ -41,8 +41,8 @@ function validateTextarea( if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); @@ -50,7 +50,7 @@ function validateTextarea( } } - const maxTextAreaLength: number = maxLength || 50; + const maxTextAreaLength: number = maxLength ?? 50; // Função interna para obter a mensagem de erro function getErrorMessage(index: number): string { @@ -61,7 +61,7 @@ function validateTextarea( if (errorMessage === "This textarea is too big") { return `Textarea cannot exceed ${maxTextAreaLength} characters`; } - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; + return errorMessage ?? defaultErrorMsg[index]; } if (maxTextAreaLength < 1 || typeof maxTextAreaLength !== "number") { diff --git a/src/validateUSPhoneNumber.ts b/src/validateUSPhoneNumber.ts index 55566ad..d4136ab 100644 --- a/src/validateUSPhoneNumber.ts +++ b/src/validateUSPhoneNumber.ts @@ -25,8 +25,8 @@ function validateUSPhoneNumber( if (errorMsg) { if (!Array.isArray(errorMsg)) throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { throw new TypeError( "All values within the array must be strings or null/undefined.", ); @@ -39,7 +39,7 @@ function validateUSPhoneNumber( // Internal function to get the error message function getErrorMessage(index: number): string { const errorMessage: string | null = errorMsg ? errorMsg[index] : null; - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; + return errorMessage ?? defaultErrorMsg[index]; } if (!phoneNumber) { diff --git a/src/validateUsername.ts b/src/validateUsername.ts index 41d82fd..0d8f9b9 100644 --- a/src/validateUsername.ts +++ b/src/validateUsername.ts @@ -58,91 +58,149 @@ function validateUsername( if (typeof username !== "string") { throw new TypeError("The input should be a string."); } - // Check para saber se as mensagens que sao passadas sao validas - // caso contrario retorna um ERRO - if (errorMsg) { - if (!Array.isArray(errorMsg)) - throw new Error("errorMsg must be an Array or null"); - for (let index: number = 0; index < errorMsg.length; index += 1) { - if (errorMsg[index] != null && typeof errorMsg[index] !== "string") { - throw new TypeError( - "All values within the array must be strings or null/undefined.", - ); - } - } - } - const minLenthUsername: number = minLength || 1; - const maxLenthUsername: number = maxLength || Infinity; - - // Função interna para obter a mensagem de erro - function getErrorMessage(index: number): string { - const errorMessage: string | null = errorMsg - ? errorMsg[index] - : defaultErrorMsg[index]; - if ( - errorMessage === "username too short" || - errorMessage === "This username is too long" - ) { - if (maxLenthUsername === Infinity) { - return `Username must be greater than ${maxLenthUsername} characters`; - } - return `Username must be between ${minLenthUsername} and ${maxLenthUsername} characters`; - } - return errorMessage != null ? errorMessage : defaultErrorMsg[index]; - } + + validateErrorMsg(errorMsg); + + const minLenthUsername: number = minLength ?? 1; + const maxLenthUsername: number = maxLength ?? Infinity; if (!username) { return { isValid: false, - errorMsg: getErrorMessage(0), + errorMsg: getErrorMessage( + 0, + errorMsg, + minLenthUsername, + maxLenthUsername, + ), }; } - if ( - typeof minLenthUsername !== "number" || - typeof maxLenthUsername !== "number" - ) { - throw new Error("maxLength or minLength must be a number"); - } - if (minLenthUsername > maxLenthUsername) { - throw new Error("Minimum cannot be greater than maximum"); - } // Verifica se o min é maior que o max - if (minLenthUsername < 1 || maxLenthUsername < 1) { - throw new Error("Size parameters cannot be less than one"); - } // Nenhum dos dois pode ser menor que 1 + validateLengthParams(minLenthUsername, maxLenthUsername); if (regexHasSpaces.test(username)) { return { isValid: false, - errorMsg: getErrorMessage(3), + errorMsg: getErrorMessage( + 3, + errorMsg, + minLenthUsername, + maxLenthUsername, + ), }; } if (regexOnlyNumbers.test(username)) { return { isValid: false, - errorMsg: getErrorMessage(5), + errorMsg: getErrorMessage( + 5, + errorMsg, + minLenthUsername, + maxLenthUsername, + ), }; } if (regexStartsWithNumber.test(username)) { return { isValid: false, - errorMsg: getErrorMessage(4), + errorMsg: getErrorMessage( + 4, + errorMsg, + minLenthUsername, + maxLenthUsername, + ), }; } if (username.length < minLenthUsername) { return { isValid: false, - errorMsg: getErrorMessage(1), + errorMsg: getErrorMessage( + 1, + errorMsg, + minLenthUsername, + maxLenthUsername, + ), }; - } // Tamanho n pode ser menor q o min + } if (username.length > maxLenthUsername) { return { isValid: false, - errorMsg: getErrorMessage(2), + errorMsg: getErrorMessage( + 2, + errorMsg, + minLenthUsername, + maxLenthUsername, + ), + }; + } + + if (containsMultipleSpecialChars(username)) { + return { + isValid: false, + errorMsg: "Username cannot contain multiple special characters", }; - } // Tamanho da palavra não pode ser maior que o tamanho máximo + } + + return { + isValid: true, + errorMsg: null, + }; +} - // Define os caracteres especiais +function validateErrorMsg(errorMsg: (string | null)[] | undefined): void { + if (errorMsg) { + if (!Array.isArray(errorMsg)) + throw new Error("errorMsg must be an Array or null"); + for (const element of errorMsg) { + if (element != null && typeof element !== "string") { + throw new TypeError( + "All values within the array must be strings or null/undefined.", + ); + } + } + } +} + +function validateLengthParams( + minLenthUsername: number, + maxLenthUsername: number, +): void { + if ( + typeof minLenthUsername !== "number" || + typeof maxLenthUsername !== "number" + ) { + throw new Error("maxLength or minLength must be a number"); + } + if (minLenthUsername > maxLenthUsername) { + throw new Error("Minimum cannot be greater than maximum"); + } + if (minLenthUsername < 1 || maxLenthUsername < 1) { + throw new Error("Size parameters cannot be less than one"); + } +} + +function getErrorMessage( + index: number, + errorMsg: (string | null)[] | undefined, + minLenthUsername: number, + maxLenthUsername: number, +): string { + const errorMessage: string | null = errorMsg + ? errorMsg[index] + : defaultErrorMsg[index]; + if ( + errorMessage === "username too short" || + errorMessage === "This username is too long" + ) { + if (maxLenthUsername === Infinity) { + return `Username must be greater than ${maxLenthUsername} characters`; + } + return `Username must be between ${minLenthUsername} and ${maxLenthUsername} characters`; + } + return errorMessage ?? defaultErrorMsg[index]; +} + +function containsMultipleSpecialChars(username: string): boolean { const specialChars: string[] = [ "!", "@", @@ -176,25 +234,16 @@ function validateUsername( "?", ]; - // Cria um objeto para contar a ocorrência de cada caractere especial const charCount: { [key: string]: number } = {}; - // Itera sobre a string para contar os caracteres especiais for (const char of username) { if (specialChars.includes(char)) { charCount[char] = (charCount[char] || 0) + 1; if (charCount[char] > 2) { - return { - isValid: false, - errorMsg: "Username cannot contain multiple special characters", - }; + return true; } } } - - return { - isValid: true, - errorMsg: null, - }; + return false; } export default validateUsername; diff --git a/tests/src/isAscii.test.ts b/tests/src/isAscii.test.ts index ff25215..fe58a8d 100644 --- a/tests/src/isAscii.test.ts +++ b/tests/src/isAscii.test.ts @@ -6,6 +6,10 @@ describe("isAscii", () => { expect(result).toBe(true); }); + it("should return true when the input is an empty string", () => { + expect(() => isAscii(" ")).toThrow("Input value must not be an empty string."); + }); + it("should return false when the input is not ASCII", () => { const result = isAscii("日本語日本語"); expect(result).toBe(false); diff --git a/tests/src/isDecimal.test.ts b/tests/src/isDecimal.test.ts index 0d5274e..4b8384f 100644 --- a/tests/src/isDecimal.test.ts +++ b/tests/src/isDecimal.test.ts @@ -73,7 +73,7 @@ describe("isDecimal", () => { }); it("should throw error when the input is a function", () => { - function func() { } + function func() { /* document why this function 'func' is empty */ } expect(() => isDecimal(func() as any) as any).toThrow(errorToThrow); }); @@ -115,13 +115,21 @@ describe("isDecimal", () => { }); it("should throw error when the input is a class", () => { - class A { } + class A { + method() { + return "This is a method"; + } + } expect(() => isDecimal(A as any)).toThrow(errorToThrow); }); it("should throw error when the input is a class instance", () => { - class A { } + class A { + method() { + return "This is a method"; + } + } expect(() => isDecimal(new A() as any)).toThrow(errorToThrow); }); @@ -183,7 +191,7 @@ describe("isDecimal", () => { }); it("should throw error when the input is a function", () => { - function func() { } + function func() { /* document why this function 'func' is empty */ } expect(() => isDecimal(func as any)).toThrow( "Input value must be a string or a number.", diff --git a/tests/src/isEmail.test.ts b/tests/src/isEmail.test.ts index 0488142..059f7c9 100644 --- a/tests/src/isEmail.test.ts +++ b/tests/src/isEmail.test.ts @@ -363,4 +363,12 @@ describe("isEmail", () => { it("returns false for email with invalid TLD", () => { expect(isEmail("foo@bar.c")).toBe(false); }); + + it("should return false when has more than one @", () => { + expect(isEmail("foo@bar.com@")).toBe(false); + }); + + it("should return false when has number after last dot", () => { + expect(isEmail("foo@bar.com.1")).toBe(false); + }); }); diff --git a/tests/src/validatePassword.test.ts b/tests/src/validatePassword.test.ts index fcbb92c..d42bbac 100644 --- a/tests/src/validatePassword.test.ts +++ b/tests/src/validatePassword.test.ts @@ -149,4 +149,32 @@ describe("validatePassword", () => { }), ).toThrow("All values within the array must be strings or null/undefined."); }); + + it("should throw an error if errorMsg is not an array", () => { + expect(() => + validatePassword("Passw0rd!", { + minLength: 8, + maxLength: 20, + errorMsg: 123 as any, + }), + ).toThrow("errorMsg must be an Array or null"); + }); + + it("should throw an error if maxLength or minLength is not a number", () => { + expect(() => + validatePassword("Passw0rd!", { + minLength: 8, + maxLength: "20" as any, + }), + ).toThrow("maxLength and/or minLength must be a number"); + }); + + it("should throw an error if minLength or maxLength is less than 1", () => { + expect(() => + validatePassword("Passw0rd!", { + minLength: 0, + maxLength: 20, + }), + ).toThrow("No size can be smaller than 1"); + }); }); diff --git a/tests/testerGeral.test.ts b/tests/testerGeral.test.ts index da4d639..d93db20 100644 --- a/tests/testerGeral.test.ts +++ b/tests/testerGeral.test.ts @@ -13,7 +13,6 @@ import { isAscii, isBase64, isDate, - isDecimal, isEmpty, isMD5, isPort,