From 52643aa430ebf027fcc772e6922fbd609a073e6b Mon Sep 17 00:00:00 2001 From: gabriel-logan Date: Sat, 24 Aug 2024 01:53:11 -0300 Subject: [PATCH] test: Covering more tests --- src/cnpjValidator.ts | 66 ++++----- src/cpfValidator.ts | 75 +++++----- src/getOnlyEmail.ts | 21 --- src/isCEP.ts | 23 ++-- src/validateBRPhoneNumber.ts | 24 ++-- src/validateEmail.ts | 71 +++++----- src/validateName.ts | 86 ++++++------ src/validatePassword.ts | 80 +++++------ src/validatePhoneNumber.ts | 22 +-- src/validateSurname.ts | 90 ++++++------ src/validateTextarea.ts | 21 +-- src/validateUSPhoneNumber.ts | 22 +-- src/validateUsername.ts | 166 +++++++++++------------ tests/src/cnpjValidator.test.ts | 20 ++- tests/src/cpfValidator.test.ts | 12 ++ tests/src/getOnlyEmail.test.ts | 16 +++ tests/src/isDate.test.ts | 5 + tests/src/isDecimal.test.ts | 28 +++- tests/src/isValidVideo.test.ts | 32 +++++ tests/src/validateEmail.test.ts | 33 ++++- tests/src/validateName.test.ts | 10 ++ tests/src/validatePassportNumber.test.ts | 6 + tests/src/validatePhoneNumber.test.ts | 12 ++ tests/src/validateSurname.test.ts | 14 ++ tests/src/validateUSPhoneNumber.test.ts | 12 ++ 25 files changed, 520 insertions(+), 447 deletions(-) diff --git a/src/cnpjValidator.ts b/src/cnpjValidator.ts index 6c8ce13..d397e70 100644 --- a/src/cnpjValidator.ts +++ b/src/cnpjValidator.ts @@ -27,7 +27,6 @@ const defaultErrorMsg: string[] = [ "CNPJ invalid", "CNPJ must have 14 numerical digits", "CNPJ is not valid", - "Unknown error", ]; /** @@ -39,7 +38,7 @@ const defaultErrorMsg: string[] = [ * If you want to use a default parameter, use null or leave Empty. * * Default: - * ['CNPJ invalid', 'CNPJ must have 14 numerical digits', 'CNPJ is not valid', 'Unknown error'] + * ['CNPJ invalid', 'CNPJ must have 14 numerical digits', 'CNPJ is not valid'] * . * * Create a list of errors separated by commas in strings @@ -75,48 +74,39 @@ function cnpjIsValid( return errorMessage != null ? errorMessage : defaultErrorMsg[index]; } - try { - if (!cnpj) { - return { - isValid: false, - errorMsg: getErrorMessage(0), // 'CNPJ invalid' - }; - } - // Check if the CNPJ has 14 digits - if (cnpj.length !== 14 && cnpj.length !== 18) { - return { - isValid: false, - errorMsg: getErrorMessage(1), // 'CNPJ must have 14 numerical digits' - }; - } - // Remove any non-digit characters from the CNPJ string - const cnpjClean: string = cnpj.replace(/\D+/g, ""); - // Convert the CNPJ string to an array of digits - const cnpjArray: number[] = cnpjClean.split("").map(Number); - // Calculate the first and second verifiers - const firstVerifier: number = calculateFirstVerifier( - cnpjArray.slice(0, 12), - ); - const secondVerifier: number = calculateSecondVerifier( - cnpjArray.slice(0, 12).concat(firstVerifier), - firstVerifier, - ); - // Check if the calculated verifiers match the ones in the CNPJ - if (cnpjArray[12] === firstVerifier && cnpjArray[13] === secondVerifier) { - return { - isValid: true, - errorMsg: null, - }; - } + if (!cnpj) { return { isValid: false, - errorMsg: getErrorMessage(2), // 'CNPJ is not valid' + errorMsg: getErrorMessage(0), // 'CNPJ invalid' }; - } catch (error) { + } + // Check if the CNPJ has 14 digits + if (cnpj.length !== 14 && cnpj.length !== 18) { return { isValid: false, - errorMsg: getErrorMessage(3), // 'Unknown error' + errorMsg: getErrorMessage(1), // 'CNPJ must have 14 numerical digits' + }; + } + // Remove any non-digit characters from the CNPJ string + const cnpjClean: string = cnpj.replace(/\D+/g, ""); + // Convert the CNPJ string to an array of digits + const cnpjArray: number[] = cnpjClean.split("").map(Number); + // Calculate the first and second verifiers + const firstVerifier: number = calculateFirstVerifier(cnpjArray.slice(0, 12)); + const secondVerifier: number = calculateSecondVerifier( + cnpjArray.slice(0, 12).concat(firstVerifier), + firstVerifier, + ); + // Check if the calculated verifiers match the ones in the CNPJ + if (cnpjArray[12] === firstVerifier && cnpjArray[13] === secondVerifier) { + return { + isValid: true, + errorMsg: null, }; } + return { + isValid: false, + errorMsg: getErrorMessage(2), // 'CNPJ is not valid' + }; } export default cnpjIsValid; diff --git a/src/cpfValidator.ts b/src/cpfValidator.ts index f93e685..353ab43 100644 --- a/src/cpfValidator.ts +++ b/src/cpfValidator.ts @@ -2,7 +2,6 @@ const defaultErrorMsg: string[] = [ "CPF invalid", "CPF must have 11 numerical digits", "CPF is not valid", - "Unknown error", ]; /** @@ -29,6 +28,7 @@ function cpfIsValid( if (typeof cpf !== "string") { throw new TypeError("The input should be a string."); } + if (errorMsg) { if (!Array.isArray(errorMsg)) throw new TypeError("Must be an Array"); for (let index: number = 0; index < errorMsg.length; index += 1) { @@ -45,56 +45,49 @@ function cpfIsValid( return errorMessage != null ? errorMessage : defaultErrorMsg[index]; } - try { - if (!cpf) { - return { - isValid: false, - errorMsg: getErrorMessage(0), - }; - } - - const cpfClean: string = cpf.replace(/\D+/g, ""); - - if (/^(\d)\1{10}$/.test(cpfClean)) { - return { - isValid: false, - errorMsg: getErrorMessage(2), - }; - } - - if (cpfClean.length !== 11) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } + if (!cpf) { + return { + isValid: false, + errorMsg: getErrorMessage(0), + }; + } - const cpfArray: number[] = cpfClean.split("").map(Number); - const validator: (sum: number) => number = (sum: number) => - sum % 11 < 2 ? 0 : 11 - (sum % 11); - const sum1: number = cpfArray - .slice(0, 9) - .reduce((acc, val, i) => acc + val * (10 - i), 0); - const sum2: number = cpfArray - .slice(0, 10) - .reduce((acc, val, i) => acc + val * (11 - i), 0); + const cpfClean: string = cpf.replace(/\D+/g, ""); - if (cpfArray[9] === validator(sum1) && cpfArray[10] === validator(sum2)) { - return { - isValid: true, - errorMsg: null, - }; - } + if (/^(\d)\1{10}$/.test(cpfClean)) { return { isValid: false, errorMsg: getErrorMessage(2), }; - } catch (err) { + } + + if (cpfClean.length !== 11) { return { isValid: false, - errorMsg: getErrorMessage(3), + errorMsg: getErrorMessage(1), + }; + } + + const cpfArray: number[] = cpfClean.split("").map(Number); + const validator: (sum: number) => number = (sum: number) => + sum % 11 < 2 ? 0 : 11 - (sum % 11); + const sum1: number = cpfArray + .slice(0, 9) + .reduce((acc, val, i) => acc + val * (10 - i), 0); + const sum2: number = cpfArray + .slice(0, 10) + .reduce((acc, val, i) => acc + val * (11 - i), 0); + + if (cpfArray[9] === validator(sum1) && cpfArray[10] === validator(sum2)) { + return { + isValid: true, + errorMsg: null, }; } + return { + isValid: false, + errorMsg: getErrorMessage(2), + }; } export default cpfIsValid; diff --git a/src/getOnlyEmail.ts b/src/getOnlyEmail.ts index c684ba4..f19aa83 100644 --- a/src/getOnlyEmail.ts +++ b/src/getOnlyEmail.ts @@ -96,27 +96,6 @@ function getOnlyEmail( } return multiple ? matches : matches[0]; - /** - * const cleanedEmails: string[] = matches.map((email) => { - for (const domain of domainsToClean) { - const index: number = email.lastIndexOf(domain); - if (index !== -1) { - return email.substring(0, index + domain.length); - } - } - return email; - }); - - const cleanedEmails2: string[] = cleanedEmails.map((email) => { - for (const domain of domainsToClean) { - const index: number = email.indexOf(domain); - if (index !== -1) { - return email.substring(0, index + domain.length); - } - } - return email; - }); - */ } export default getOnlyEmail; diff --git a/src/isCEP.ts b/src/isCEP.ts index 6cb913b..d37fee3 100644 --- a/src/isCEP.ts +++ b/src/isCEP.ts @@ -7,17 +7,20 @@ function isCEP(cep: string): boolean { if (typeof cep !== "string") { throw new TypeError("Input value must be a string."); } - try { - if (cep.length < 8 || cep.length > 10) return false; - // Clean the CEP and keep only the numbers - const cepString: string = cep.replace(/\D/g, ""); // The \D pattern matches any non-digit character - // Check if the cleaned CEP contains only numbers - if (cepString.length !== 8) return false; - // Check if the CEP is a valid number (all digits) - if (Number.isNaN(cepString)) return false; - return true; - } catch (error) { + if (cep.length < 8 || cep.length > 10) { return false; } + // Clean the CEP and keep only the numbers + const cepString: string = cep.replace(/\D/g, ""); // The \D pattern matches any non-digit character + // Check if the cleaned CEP contains only numbers + if (cepString.length !== 8) { + return false; + } + // Check if the CEP is a valid number (all digits) + if (Number.isNaN(cepString)) { + return false; + } + + return true; } export default isCEP; diff --git a/src/validateBRPhoneNumber.ts b/src/validateBRPhoneNumber.ts index a7bfeb4..979fbc0 100644 --- a/src/validateBRPhoneNumber.ts +++ b/src/validateBRPhoneNumber.ts @@ -3,17 +3,16 @@ import { ValidateFunctions } from "./types"; const defaultErrorMsg: string[] = [ "Field phone number cannot be empty", "Invalid phone number", - "Unknown error", ]; /** * @param phoneNumber * @param errorMsg optional * @example validateBRPhoneNumber('(11) 98765-4321'); - * @example validateBRPhoneNumber('(11) 98765-4321', ['Invalid phone number', 'Invalid format', 'Unknown error']); + * @example validateBRPhoneNumber('(11) 98765-4321', ['Invalid phone number', 'Invalid format']); * @description This function returns three errors in the following order: * * Default: - * ['Field phone number cannot be empty', 'Invalid phone number', 'Unknown error'] + * ['Field phone number cannot be empty', 'Invalid phone number'] * * Create a list of errors separated by commas in strings * @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties. @@ -51,22 +50,15 @@ function validateBRPhoneNumber( } // Regular expression to validate Brazilian phone numbers const brPhoneNumberRegex: RegExp = /^\(\d{2}\) \d{5}-\d{4}$/; - try { - if (!brPhoneNumberRegex.test(phoneNumber)) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } - return { - isValid: true, - errorMsg: null, - }; - } catch (error) { + if (!brPhoneNumberRegex.test(phoneNumber)) { return { isValid: false, - errorMsg: getErrorMessage(2), + errorMsg: getErrorMessage(1), }; } + return { + isValid: true, + errorMsg: null, + }; } export default validateBRPhoneNumber; diff --git a/src/validateEmail.ts b/src/validateEmail.ts index 96a546c..9aced8b 100644 --- a/src/validateEmail.ts +++ b/src/validateEmail.ts @@ -7,7 +7,6 @@ const defaultErrorMsg: string[] = [ "Email too big, try again", "This email is not valid in the country", "Email domain is not allowed.", - "Unknown error", ]; const validDomainsDefault: string[] = [ @@ -55,7 +54,7 @@ const defaultOptionsParams: OptionsParams = { * If you want to use a default parameter, use null. * * Default: - * ['Email cannot be empty', 'This e-mail is not valid', 'Email cannot be greater than ${maxEmailLength} characters', 'This email is not valid in the country','Email domain is not allowed.', 'Unknown error'] + * ['Email cannot be empty', 'This e-mail is not valid', 'Email cannot be greater than ${maxEmailLength} characters', 'This email is not valid in the country','Email domain is not allowed.'] * * Create a list of errors separated by commas in strings * @@ -110,6 +109,12 @@ function validateEmail( } } + 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 @@ -130,47 +135,37 @@ function validateEmail( }; } - if (maxEmailLength < 1 || typeof maxEmailLength !== "number") - throw new Error("maxLength must be a number and cannot be less than 1"); - - try { - // Check domain only if regex is defined (validDomains is true or validDomains is an array) - if (!regex.test(email)) { - return { - isValid: false, - errorMsg: getErrorMessage(4), - }; - } - if (!isEmail(email)) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } - if (email.length > maxEmailLength) { - return { - isValid: false, - errorMsg: getErrorMessage(2), - }; - } - // 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), - }; - } - } + // Check domain only if regex is defined (validDomains is true or validDomains is an array) + if (!regex.test(email)) { + return { + isValid: false, + errorMsg: getErrorMessage(4), + }; + } + if (!isEmail(email)) { return { - isValid: true, - errorMsg: null, + isValid: false, + errorMsg: getErrorMessage(1), }; - } catch (error) { + } + if (email.length > maxEmailLength) { return { isValid: false, - errorMsg: getErrorMessage(5), + errorMsg: getErrorMessage(2), }; } + // 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), + }; + } + } + return { + isValid: true, + errorMsg: null, + }; } export default validateEmail; diff --git a/src/validateName.ts b/src/validateName.ts index da78cbc..a0b0ee1 100644 --- a/src/validateName.ts +++ b/src/validateName.ts @@ -6,7 +6,6 @@ const defaultErrorMsg: string[] = [ "Name cannot contain special characters", "This name is not valid", "Name too big, try again", - "Unknown error", ]; interface OptionsParams { @@ -40,7 +39,6 @@ const defaultOptionsParams: OptionsParams = { 'Name cannot contain special characters', 'This name is not valid', 'Name too big, try again', - 'Unknown error', ]; * @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties. */ @@ -95,61 +93,55 @@ function validateName( errorMsg: getErrorMessage(0), }; } - try { - 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.length > maxNameLength) { + return { + isValid: false, + errorMsg: getErrorMessage(4), + }; + } - if (name.match(/[^\w\s]/)) { - return { - isValid: false, - errorMsg: getErrorMessage(2), - }; - } + if (name.length < minNameLength) { + return { + isValid: false, + errorMsg: getErrorMessage(3), + }; + } - // 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. - }; - } + if (name.match(/\d/)) { + return { + isValid: false, + errorMsg: getErrorMessage(1), + }; + } - // 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. - }; - } + 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: true, - errorMsg: null, + isValid: false, + errorMsg: getErrorMessage(3), // Assuming 'Name is not allowed.' refers to all characters being repeated. }; - } catch (error) { + } + + // 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(5), + errorMsg: getErrorMessage(3), // You can set the appropriate error message for this case. }; } + + return { + isValid: true, + errorMsg: null, + }; } export default validateName; diff --git a/src/validatePassword.ts b/src/validatePassword.ts index afde7a2..e042073 100644 --- a/src/validatePassword.ts +++ b/src/validatePassword.ts @@ -7,7 +7,6 @@ const defaultErrorMsg: string[] = [ "Password requires at least one special character", "Password requires at least one number", "Password requires at least one letter", - "Unknown error", ]; interface Options { @@ -66,7 +65,6 @@ const defaultOptionsParams: OptionsParams = { 'Requires at least one special character', 'Requires at least one number', 'Requires at least one letter', - 'Unknown error', ]; * @@ -134,56 +132,46 @@ function validatePassword( throw new Error("No size can be smaller than 1"); } // Nenhum dos dois pode ser menor que 1 - try { - if (password.length > maxLenthPassword) { - return { - isValid: false, - errorMsg: getErrorMessage(0), - }; - } // Tamanho da palavra não pode ser maior que o tamanho máximo - if (password.length < minLenthPassword) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } // Tamanho n pode ser menor q o min - if (options?.requireUppercase && !/[A-Z]/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(2), // Requer pelo menos uma letra maiuscula - }; - } - if ( - options?.requireSpecialChar && - !/[!@#$%^&*(),.?":{}|<>]/.test(password) - ) { - return { - isValid: false, - errorMsg: getErrorMessage(3), // Requer pelo menos uma especial caracter - }; - } - if (options?.requireNumber && !/\d/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(4), // Requer pelo menos um numero - }; - } - if (options?.requireString && !/[a-zA-Z]/.test(password)) { - return { - isValid: false, - errorMsg: getErrorMessage(5), // Requer pelo menos uma letra - }; - } + if (password.length > maxLenthPassword) { + return { + isValid: false, + errorMsg: getErrorMessage(0), + }; + } // Tamanho da palavra não pode ser maior que o tamanho máximo + if (password.length < minLenthPassword) { + return { + isValid: false, + errorMsg: getErrorMessage(1), + }; + } // Tamanho n pode ser menor q o min + if (options?.requireUppercase && !/[A-Z]/.test(password)) { + return { + isValid: false, + errorMsg: getErrorMessage(2), // Requer pelo menos uma letra maiuscula + }; + } + if (options?.requireSpecialChar && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) { return { - isValid: true, - errorMsg: null, + isValid: false, + errorMsg: getErrorMessage(3), // Requer pelo menos uma especial caracter }; - } catch (error) { + } + if (options?.requireNumber && !/\d/.test(password)) { + return { + isValid: false, + errorMsg: getErrorMessage(4), // Requer pelo menos um numero + }; + } + if (options?.requireString && !/[a-zA-Z]/.test(password)) { return { isValid: false, - errorMsg: getErrorMessage(6), + errorMsg: getErrorMessage(5), // Requer pelo menos uma letra }; } + return { + isValid: true, + errorMsg: null, + }; } export default validatePassword; diff --git a/src/validatePhoneNumber.ts b/src/validatePhoneNumber.ts index 18b233a..4043302 100644 --- a/src/validatePhoneNumber.ts +++ b/src/validatePhoneNumber.ts @@ -3,14 +3,13 @@ import { ValidateFunctions } from "./types"; const defaultErrorMsg: string[] = [ "Phone number cannot be empty", "Invalid phone number", - "Unknown error", ]; /** * @param phoneNumber * @param errorMsg optional * @example validatePhoneNumber('555-123-4567'); * @example validatePhoneNumber('(555) 123-4567', [null, 'Custom error 2']); - * @default {errorMsg} ['Phone number cannot be empty', 'Invalid phone number', 'Unknown error'] + * @default {errorMsg} ['Phone number cannot be empty', 'Invalid phone number'] * @description This function is a generic phone number validator. It can validate phone numbers in various formats depending on the specific implementation. * @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties. */ @@ -52,22 +51,15 @@ function validatePhoneNumber( // Updated regular expression for phone number validation const phoneNumberRegex: RegExp = /^\(\d{3}\) \d{3}-\d{4}$/; - try { - if (!phoneNumberRegex.test(phoneNumber)) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } - return { - isValid: true, - errorMsg: null, - }; - } catch (error) { + if (!phoneNumberRegex.test(phoneNumber)) { return { isValid: false, - errorMsg: getErrorMessage(2), + errorMsg: getErrorMessage(1), }; } + return { + isValid: true, + errorMsg: null, + }; } export default validatePhoneNumber; diff --git a/src/validateSurname.ts b/src/validateSurname.ts index 5b41a86..c80c481 100644 --- a/src/validateSurname.ts +++ b/src/validateSurname.ts @@ -6,7 +6,6 @@ const defaultErrorMsg: string[] = [ "Surname cannot contain special characters", "This surname is not valid", "Surname too big, try again", - "Unknown error", ]; interface OptionsParams { @@ -40,7 +39,6 @@ const defaultOptionsParams: OptionsParams = { 'Surname cannot contain special characters', 'This surname is not valid', 'Surname too big, try again', - 'Unknown error', ]; * @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties. */ @@ -56,8 +54,9 @@ function validateSurname( // caso contrario retorna um ERRO if (errorMsg) { - if (!Array.isArray(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( @@ -98,60 +97,53 @@ function validateSurname( }; } - try { - 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), - }; - } + if (surname.length > maxNameLength) { + return { + isValid: false, + errorMsg: getErrorMessage(4), + }; + } + if (surname.length < minNameLength) { + return { + isValid: false, + errorMsg: getErrorMessage(3), + }; + } - // 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. - }; - } + if (surname.match(/\d/)) { + return { + isValid: false, + errorMsg: getErrorMessage(1), + }; + } - // 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. - }; - } + 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: true, - errorMsg: null, + isValid: false, + errorMsg: getErrorMessage(3), // Assuming 'Surname is not allowed.' refers to all characters being repeated. }; - } catch (error) { + } + + // 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(5), + errorMsg: getErrorMessage(3), // You can set the appropriate error message for this case. }; } + + return { + isValid: true, + errorMsg: null, + }; } export default validateSurname; diff --git a/src/validateTextarea.ts b/src/validateTextarea.ts index 3615410..19a7c93 100644 --- a/src/validateTextarea.ts +++ b/src/validateTextarea.ts @@ -3,7 +3,6 @@ import { ValidateFunctions } from "./types"; const defaultErrorMsg: string[] = [ "This textarea is too big", "Can not be empty", - "Unknown error", ]; interface OptionsParams { @@ -27,7 +26,6 @@ const defaultOptionsParams: OptionsParams = { * [ 'Textarea cannot exceed ${maxTextAreaLength} characters', 'Can not be empty', - 'Unknown error', ]; * @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties. */ @@ -78,22 +76,15 @@ function validateTextarea( }; } - try { - if (textarea.length > maxTextAreaLength) { - return { - isValid: false, - errorMsg: getErrorMessage(0), - }; - } - return { - isValid: true, - errorMsg: null, - }; - } catch (error) { + if (textarea.length > maxTextAreaLength) { return { isValid: false, - errorMsg: getErrorMessage(2), + errorMsg: getErrorMessage(0), }; } + return { + isValid: true, + errorMsg: null, + }; } export default validateTextarea; diff --git a/src/validateUSPhoneNumber.ts b/src/validateUSPhoneNumber.ts index db434a6..55566ad 100644 --- a/src/validateUSPhoneNumber.ts +++ b/src/validateUSPhoneNumber.ts @@ -3,7 +3,6 @@ import { ValidateFunctions } from "./types"; const defaultErrorMsg: string[] = [ "US phone number cannot be empty", "Invalid phone number", - "Unknown error", ]; /** @@ -12,7 +11,7 @@ const defaultErrorMsg: string[] = [ * @example validateUSPhoneNumber('555-123-4567'); * @example validateUSPhoneNumber('(555) 123-4567', [null, 'Custom error 2']); * @description This function validates phone numbers in the USA. It supports various formats, including "XXX-XXX-XXXX", "(XXX) XXX-XXXX", and "1 (XXX) XXX-XXXX". - * @default {errorMsg} "['US phone number cannot be empty', 'Invalid phone number', 'Unknown error']" + * @default {errorMsg} "['US phone number cannot be empty', 'Invalid phone number']" * @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties. */ function validateUSPhoneNumber( @@ -49,23 +48,16 @@ function validateUSPhoneNumber( errorMsg: getErrorMessage(0), }; } - try { - if (!usPhoneNumberRegex.test(phoneNumber)) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } - return { - isValid: true, - errorMsg: null, - }; - } catch (error) { + if (!usPhoneNumberRegex.test(phoneNumber)) { return { isValid: false, - errorMsg: getErrorMessage(2), + errorMsg: getErrorMessage(1), }; } + return { + isValid: true, + errorMsg: null, + }; } export default validateUSPhoneNumber; diff --git a/src/validateUsername.ts b/src/validateUsername.ts index 30f3c7e..41d82fd 100644 --- a/src/validateUsername.ts +++ b/src/validateUsername.ts @@ -10,7 +10,6 @@ const defaultErrorMsg: string[] = [ "Username cannot contain spaces", "Cannot start with a number", "Cannot contain only numbers", - "Unknown error", ]; interface OptionsParams { @@ -47,7 +46,6 @@ const defaultOptionsParams: OptionsParams = { 'Username cannot contain spaces', 'Cannot start with a number', 'Cannot contain only numbers', - 'Unknown error' ]; * * Create a list of errors separated by commas in strings @@ -112,97 +110,91 @@ function validateUsername( if (minLenthUsername < 1 || maxLenthUsername < 1) { throw new Error("Size parameters cannot be less than one"); } // Nenhum dos dois pode ser menor que 1 - try { - if (regexHasSpaces.test(username)) { - return { - isValid: false, - errorMsg: getErrorMessage(3), - }; - } - if (regexOnlyNumbers.test(username)) { - return { - isValid: false, - errorMsg: getErrorMessage(5), - }; - } - if (regexStartsWithNumber.test(username)) { - return { - isValid: false, - errorMsg: getErrorMessage(4), - }; - } - if (username.length < minLenthUsername) { - return { - isValid: false, - errorMsg: getErrorMessage(1), - }; - } // Tamanho n pode ser menor q o min - if (username.length > maxLenthUsername) { - return { - isValid: false, - errorMsg: getErrorMessage(2), - }; - } // Tamanho da palavra não pode ser maior que o tamanho máximo - - // Define os caracteres especiais - const specialChars: string[] = [ - "!", - "@", - "#", - "$", - "%", - "^", - "&", - "*", - "(", - ")", - "-", - "_", - "=", - "+", - "[", - "]", - "{", - "}", - "|", - "\\", - ";", - ":", - "'", - '"', - ",", - ".", - "<", - ">", - "/", - "?", - ]; - - // 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", - }; - } - } - } + if (regexHasSpaces.test(username)) { return { - isValid: true, - errorMsg: null, + isValid: false, + errorMsg: getErrorMessage(3), }; - } catch (error) { + } + if (regexOnlyNumbers.test(username)) { + return { + isValid: false, + errorMsg: getErrorMessage(5), + }; + } + if (regexStartsWithNumber.test(username)) { return { isValid: false, - errorMsg: getErrorMessage(6), + errorMsg: getErrorMessage(4), }; } + if (username.length < minLenthUsername) { + return { + isValid: false, + errorMsg: getErrorMessage(1), + }; + } // Tamanho n pode ser menor q o min + if (username.length > maxLenthUsername) { + return { + isValid: false, + errorMsg: getErrorMessage(2), + }; + } // Tamanho da palavra não pode ser maior que o tamanho máximo + + // Define os caracteres especiais + const specialChars: string[] = [ + "!", + "@", + "#", + "$", + "%", + "^", + "&", + "*", + "(", + ")", + "-", + "_", + "=", + "+", + "[", + "]", + "{", + "}", + "|", + "\\", + ";", + ":", + "'", + '"', + ",", + ".", + "<", + ">", + "/", + "?", + ]; + + // 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 { + isValid: true, + errorMsg: null, + }; } export default validateUsername; diff --git a/tests/src/cnpjValidator.test.ts b/tests/src/cnpjValidator.test.ts index 24cd41a..9dc5172 100644 --- a/tests/src/cnpjValidator.test.ts +++ b/tests/src/cnpjValidator.test.ts @@ -13,14 +13,20 @@ describe("cnpjIsValid function", () => { expect(result.errorMsg).toBe("CNPJ is not valid"); }); - test("should invalidate a CNPJ with incorrect length", () => { - const result = cnpjIsValid("1234567890123"); + test("should invalidate a CNPJ with non-digit characters", () => { + const result = cnpjIsValid("72.501.263/0001-4A"); + expect(result.isValid).toBe(false); + expect(result.errorMsg).toBe("CNPJ is not valid"); + }); + + test("should return false if cnpj length is not 14 or 18", () => { + const result = cnpjIsValid("123456789012"); expect(result.isValid).toBe(false); expect(result.errorMsg).toBe("CNPJ must have 14 numerical digits"); }); - test("should invalidate a CNPJ with non-digit characters", () => { - const result = cnpjIsValid("72.501.263/0001-4A"); + test("should return false if cnpj has valid length but invalid verifier digits", () => { + const result = cnpjIsValid("12.345.678/0001-00"); expect(result.isValid).toBe(false); expect(result.errorMsg).toBe("CNPJ is not valid"); }); @@ -67,4 +73,10 @@ describe("cnpjIsValid function", () => { expect(result.isValid).toBe(false); expect(result.errorMsg).toBe("CNPJ is not valid"); }); + + test("should return false when all digits are the same", () => { + const result = cnpjIsValid("11.111.111/1111-11"); + expect(result.isValid).toBe(false); + expect(result.errorMsg).toBe("CNPJ is not valid"); + }); }); diff --git a/tests/src/cpfValidator.test.ts b/tests/src/cpfValidator.test.ts index 524a7dc..330d2de 100644 --- a/tests/src/cpfValidator.test.ts +++ b/tests/src/cpfValidator.test.ts @@ -60,4 +60,16 @@ describe("cpfIsValid", () => { expect(result.isValid).toBe(false); expect(result.errorMsg).toBe("CPF is not valid"); }); + + it("should return isValid as false and the correct error message when CPF is null or empty", () => { + let result = cpfIsValid(""); + expect(result.isValid).toBe(false); + + expect(() => cpfIsValid(null as any)).toThrow("The input should be a string."); + }); + + it("should return isValid as false and the correct error message when CPF does not have 11 digits after cleaning", () => { + const result = cpfIsValid("123.456.789-0"); + expect(result.isValid).toBe(false); + }); }); diff --git a/tests/src/getOnlyEmail.test.ts b/tests/src/getOnlyEmail.test.ts index ca4a51b..c7f9cfd 100644 --- a/tests/src/getOnlyEmail.test.ts +++ b/tests/src/getOnlyEmail.test.ts @@ -72,4 +72,20 @@ describe("getOnlyEmail", () => { ); expect(result).toBe("alexa@google.com"); }); + + it('should clean the domain from the email when cleanDomain is true', () => { + const result = getOnlyEmail( + "Entre em contato com a equipe: alexa@google.com.br", + { cleanDomain: true } + ); + expect(result).toBe("alexa@google.com.br"); + }); + + it('should clean the domain from the email using a custom domain list', () => { + const result = getOnlyEmail( + "Entre em contato com a equipe: alexa@google.custom", + { cleanDomain: [".custom"] } + ); + expect(result).toBe("alexa@google.custom"); + }); }); diff --git a/tests/src/isDate.test.ts b/tests/src/isDate.test.ts index d594e86..5852919 100644 --- a/tests/src/isDate.test.ts +++ b/tests/src/isDate.test.ts @@ -12,4 +12,9 @@ describe("isDate", () => { "Input value must be a string.", ); }); + + it("should throw an error when the input is a empty string", () => { + expect(() => isDate("")).toThrow("Input value must not be an empty string."); + expect(() => isDate(" ")).toThrow("Input value must not be an empty string."); + }); }); diff --git a/tests/src/isDecimal.test.ts b/tests/src/isDecimal.test.ts index 6f34e2d..0d5274e 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() { } expect(() => isDecimal(func() as any) as any).toThrow(errorToThrow); }); @@ -115,13 +115,13 @@ describe("isDecimal", () => { }); it("should throw error when the input is a class", () => { - class A {} + class A { } expect(() => isDecimal(A as any)).toThrow(errorToThrow); }); it("should throw error when the input is a class instance", () => { - class A {} + class A { } expect(() => isDecimal(new A() as any)).toThrow(errorToThrow); }); @@ -183,7 +183,7 @@ describe("isDecimal", () => { }); it("should throw error when the input is a function", () => { - function func() {} + function func() { } expect(() => isDecimal(func as any)).toThrow( "Input value must be a string or a number.", @@ -195,4 +195,24 @@ describe("isDecimal", () => { "Input value must be a string or a number.", ); }); + + it("should return false when the input contains both decimal separators", () => { + const result = isDecimal("1.234,56"); + expect(result).toBe(false); + }); + + it("should return false when the input contains both decimal separators in reverse order", () => { + const result = isDecimal("1,234.56"); + expect(result).toBe(false); + }); + + it("should return false when the input starts with a negative sign and has another negative sign elsewhere", () => { + const result = isDecimal("-1-23.45"); + expect(result).toBe(false); + }); + + it("should return true when the input starts with a negative sign and has only one negative sign at the beginning", () => { + const result = isDecimal("-123.45"); + expect(result).toBe(true); + }); }); diff --git a/tests/src/isValidVideo.test.ts b/tests/src/isValidVideo.test.ts index dcf8e64..a88a0f9 100644 --- a/tests/src/isValidVideo.test.ts +++ b/tests/src/isValidVideo.test.ts @@ -170,4 +170,36 @@ describe("isValidVideo", () => { expect(result2).toBe(false); expect(result1).toBe(false); }); + + test('validateMp4 should return true for specific byte sequence', () => { + const fileBuffer = Buffer.from([ + 0x00, 0x00, 0x00, 0x18, // First 4 bytes + 0x66, 0x74, 0x79, 0x70 // Next 4 bytes + ]); + + const result = isValidVideo(fileBuffer); + expect(result).toBe(true); + }); + + test('validateMp4 should return true for byte sequence 1', () => { + const fileBuffer = Buffer.from([ + 0x00, 0x00, 0x00, 0x20, // First 4 bytes + 0x66, 0x74, 0x79, 0x70, // Next 4 bytes + 0x6d, 0x70, 0x34, 0x32 // Last 4 bytes + ]); + + const result = isValidVideo(fileBuffer); + expect(result).toBe(true); + }); + + test('validateMp4 should return true for byte sequence 2', () => { + const fileBuffer = Buffer.from([ + 0x00, 0x00, 0x00, 0x1c, // First 4 bytes + 0x66, 0x74, 0x79, 0x70, // Next 4 bytes + 0x69, 0x73, 0x6f, 0x6d // Last 4 bytes + ]); + + const result = isValidVideo(fileBuffer); + expect(result).toBe(true); + }); }); diff --git a/tests/src/validateEmail.test.ts b/tests/src/validateEmail.test.ts index 2e96450..5b25d2a 100644 --- a/tests/src/validateEmail.test.ts +++ b/tests/src/validateEmail.test.ts @@ -74,4 +74,35 @@ describe("validateEmail", () => { expect(result.isValid).toBe(false); expect(result.errorMsg).toBe("Email cannot be greater than 400 characters"); }); -}); + + it("should return false when an empty string is passed", () => { + const result = validateEmail(""); + expect(result.isValid).toBe(false); + expect(result.errorMsg).toBe("Email cannot be empty"); + }); + + it("should throw an error when errorMsg is not an array or null", () => { + // @ts-ignore + expect(() => validateEmail("jor@dio.com", { errorMsg: 123 })).toThrow("errorMsg must be an Array or null"); + }); + + it("should throw an error if any element of the errorMsg array is different from string or null", () => { + expect(() => validateEmail("jd@dio.com", { errorMsg: [123 as any] })).toThrow("All values within the array must be strings or null/undefined."); + }) + + it("should throw an error when maxLength must be a number and cannot be less than 1", () => { + expect(() => validateEmail("aa@dao.com", { maxLength: 0 })).toThrow("maxLength must be a number and cannot be less than 1"); + }); + + it("should invalidate an email that does not end with the country code", () => { + const result = validateEmail("test@gmail.com", { country: "us" }); + expect(result.isValid).toBe(false); + expect(result.errorMsg).toBe("This email is not valid in the country"); + }); + + it("should validate an email that ends with the country code", () => { + const result = validateEmail("test@gmail.com.us", { country: "us" }); + expect(result.isValid).toBe(true); + expect(result.errorMsg).toBe(null); + }); +}); \ No newline at end of file diff --git a/tests/src/validateName.test.ts b/tests/src/validateName.test.ts index 8872c60..4fec29b 100644 --- a/tests/src/validateName.test.ts +++ b/tests/src/validateName.test.ts @@ -77,4 +77,14 @@ describe("validateName", () => { expect(result2.isValid).toBe(true); expect(result3.isValid).toBe(true); }); + + it("should throw an error when errorMsg not be an Array or null", () => { + expect(() => + validateName("John", { + minLength: 1, + maxLength: 20, + errorMsg: "error" as unknown as string[], + }), + ).toThrow("errorMsg must be an Array or null"); + }); }); diff --git a/tests/src/validatePassportNumber.test.ts b/tests/src/validatePassportNumber.test.ts index 859f810..194d68e 100644 --- a/tests/src/validatePassportNumber.test.ts +++ b/tests/src/validatePassportNumber.test.ts @@ -17,4 +17,10 @@ describe("validatePassportNumber", () => { const result = validatePassportNumber("123"); expect(result).toEqual({ isValid: false, country: null }); }); + + it("should throw an error when the input is not a string", () => { + expect(() => validatePassportNumber(123 as unknown as string)).toThrow( + "The input should be a string.", + ); + }); }); diff --git a/tests/src/validatePhoneNumber.test.ts b/tests/src/validatePhoneNumber.test.ts index 565705b..b3ab51c 100644 --- a/tests/src/validatePhoneNumber.test.ts +++ b/tests/src/validatePhoneNumber.test.ts @@ -32,4 +32,16 @@ describe("validatePhoneNumber", () => { "All values within the array must be strings or null/undefined.", ); }); + + it("should throw an error when errorMsg is not an array or null", () => { + expect(() => validatePhoneNumber("(555) 123-4567", "Custom error" as any)).toThrow( + "errorMsg must be an Array or null", + ); + }); + + it("should throw an error when the input is not a string", () => { + expect(() => validatePhoneNumber(123 as unknown as string)).toThrow( + "The input should be a string.", + ); + }); }); diff --git a/tests/src/validateSurname.test.ts b/tests/src/validateSurname.test.ts index 0b9d9a2..fd7d962 100644 --- a/tests/src/validateSurname.test.ts +++ b/tests/src/validateSurname.test.ts @@ -87,4 +87,18 @@ describe("validateSurname", () => { expect(result2.isValid).toBe(true); expect(result3.isValid).toBe(true); }); + + it("should throw an error when errorMsg is not an array or null", () => { + expect(() => validateSurname("Johnson", { + errorMsg: "Custom error" as unknown as (string | null)[], + })).toThrow( + "errorMsg must be an Array or null", + ); + }); + + it("should throw an error when the input is not a string", () => { + expect(() => validateSurname(123 as unknown as string)).toThrow( + "The input should be a string.", + ); + }); }); diff --git a/tests/src/validateUSPhoneNumber.test.ts b/tests/src/validateUSPhoneNumber.test.ts index 36ed773..4b9e4ae 100644 --- a/tests/src/validateUSPhoneNumber.test.ts +++ b/tests/src/validateUSPhoneNumber.test.ts @@ -32,4 +32,16 @@ describe("validateUSPhoneNumber", () => { "All values within the array must be strings or null/undefined.", ); }); + + it("should throw an error when errorMsg is not an array or null", () => { + expect(() => validateUSPhoneNumber("(555) 123-4567", "error msg" as any)).toThrow( + "errorMsg must be an Array or null", + ); + }); + + it("should throw an error when the input is not a string", () => { + expect(() => validateUSPhoneNumber(123 as unknown as string)).toThrow( + "The input should be a string.", + ); + }); });