@arkyn/shared 3.0.1-beta.8 → 3.0.1-beta.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +452 -67
  2. package/dist/bundle.js +2337 -0
  3. package/dist/bundle.umd.cjs +6 -0
  4. package/dist/formats/formatToCapitalizeFirstWordLetter.d.ts +35 -0
  5. package/dist/formats/formatToCapitalizeFirstWordLetter.d.ts.map +1 -0
  6. package/dist/formats/formatToCapitalizeFirstWordLetter.js +42 -0
  7. package/dist/index.d.ts +2 -7
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -8
  10. package/dist/services/isHtml.d.ts +22 -0
  11. package/dist/services/isHtml.d.ts.map +1 -0
  12. package/dist/services/isHtml.js +24 -0
  13. package/package.json +26 -6
  14. package/dist/validations/validateCep.d.ts +0 -24
  15. package/dist/validations/validateCep.d.ts.map +0 -1
  16. package/dist/validations/validateCep.js +0 -33
  17. package/dist/validations/validateCnpj.d.ts +0 -22
  18. package/dist/validations/validateCnpj.d.ts.map +0 -1
  19. package/dist/validations/validateCnpj.js +0 -52
  20. package/dist/validations/validateCpf.d.ts +0 -24
  21. package/dist/validations/validateCpf.d.ts.map +0 -1
  22. package/dist/validations/validateCpf.js +0 -54
  23. package/dist/validations/validateDate.d.ts +0 -34
  24. package/dist/validations/validateDate.d.ts.map +0 -1
  25. package/dist/validations/validateDate.js +0 -73
  26. package/dist/validations/validatePassword.d.ts +0 -21
  27. package/dist/validations/validatePassword.d.ts.map +0 -1
  28. package/dist/validations/validatePassword.js +0 -34
  29. package/dist/validations/validatePhone.d.ts +0 -29
  30. package/dist/validations/validatePhone.d.ts.map +0 -1
  31. package/dist/validations/validatePhone.js +0 -44
  32. package/dist/validations/validateRg.d.ts +0 -22
  33. package/dist/validations/validateRg.d.ts.map +0 -1
  34. package/dist/validations/validateRg.js +0 -31
  35. package/src/formats/formatDate.ts +0 -92
  36. package/src/formats/formatJsonObject.ts +0 -90
  37. package/src/formats/formatJsonString.ts +0 -50
  38. package/src/formats/formatToCep.ts +0 -39
  39. package/src/formats/formatToCnpj.ts +0 -40
  40. package/src/formats/formatToCpf.ts +0 -40
  41. package/src/formats/formatToCpfCnpj.ts +0 -38
  42. package/src/formats/formatToCurrency.ts +0 -63
  43. package/src/formats/formatToDate.ts +0 -70
  44. package/src/formats/formatToEllipsis.ts +0 -25
  45. package/src/formats/formatToHiddenDigits.ts +0 -92
  46. package/src/formats/formatToPhone.ts +0 -170
  47. package/src/generators/generateColorByString.ts +0 -33
  48. package/src/generators/generateId.ts +0 -61
  49. package/src/generators/generateSlug.ts +0 -31
  50. package/src/index.ts +0 -36
  51. package/src/services/calculateCardInstallment.ts +0 -73
  52. package/src/services/ensureQuotes.ts +0 -25
  53. package/src/services/maskSensitiveData.ts +0 -68
  54. package/src/services/removeCurrencySymbols.ts +0 -29
  55. package/src/services/removeNonNumeric.ts +0 -20
  56. package/src/services/stripHtmlTags.ts +0 -20
  57. package/src/services/truncateLargeFields.ts +0 -69
  58. package/src/validations/validateCep.ts +0 -41
  59. package/src/validations/validateCnpj.ts +0 -65
  60. package/src/validations/validateCpf.ts +0 -62
  61. package/src/validations/validateDate.ts +0 -86
  62. package/src/validations/validatePassword.ts +0 -41
  63. package/src/validations/validatePhone.ts +0 -50
  64. package/src/validations/validateRg.ts +0 -37
  65. package/tsconfig.json +0 -20
  66. package/vitest.config.ts +0 -5
@@ -1,73 +0,0 @@
1
- type CalculateCardInstallmentFunction = (props: {
2
- cashPrice: number;
3
- numberInstallments: number;
4
- fees?: number;
5
- }) => {
6
- totalPrice: number;
7
- installmentPrice: number;
8
- };
9
-
10
- /**
11
- * Calculates the installment price and total price for a card payment plan.
12
- *
13
- * @remarks
14
- * **Important:** When the interest amount (`fees`) is equal to 0 or the number of installments (`numberInstallments`) is equal to 1, no interest will be charged.
15
- *
16
- * @throws Will throw an error if the number of installments is less than or equal to 0.
17
- * @throws Will throw an error if the fees are less than 0.
18
- *
19
- * @param props - The input parameters for the calculation.
20
- * @param props.cashPrice - The total cash price of the product or service.
21
- * @param props.numberInstallments - The number of installments for the payment plan.
22
- * @param props.fees - The interest rate per installment (default is 0.0349).
23
- *
24
- * @returns An object containing:
25
- * - `totalPrice`: The total price to be paid, rounded to two decimal places.
26
- * - `installmentPrice`: The price of each installment, rounded to two decimal places.
27
- *
28
- * @example
29
- * ```typescript
30
- * const result = calculateCardInstallment({
31
- * cashPrice: 1000,
32
- * numberInstallments: 12,
33
- * fees: 0.02,
34
- * });
35
- * console.log(result);
36
- * // Output: { totalPrice: 1124.62, installmentPrice: 93.72 }
37
- * ```
38
- */
39
-
40
- const calculateCardInstallment: CalculateCardInstallmentFunction = (props) => {
41
- const { cashPrice, numberInstallments, fees = 0.0349 } = props;
42
-
43
- if (fees === 0 || numberInstallments === 1) {
44
- return {
45
- totalPrice: cashPrice,
46
- installmentPrice: cashPrice / numberInstallments,
47
- };
48
- }
49
-
50
- if (numberInstallments <= 0) {
51
- throw new Error("Number of installments must be greater than 0");
52
- }
53
-
54
- if (fees < 0) {
55
- throw new Error("Fees must be greater than or equal to 0");
56
- }
57
-
58
- let installmentPrice = 0;
59
- let totalPrice = 0;
60
-
61
- let numerator = Math.pow(1 + fees, numberInstallments) * fees;
62
- let denominator = Math.pow(1 + fees, numberInstallments) - 1;
63
-
64
- installmentPrice = cashPrice * (numerator / denominator);
65
- totalPrice = numberInstallments * installmentPrice;
66
-
67
- return {
68
- totalPrice: +totalPrice.toFixed(2),
69
- installmentPrice: +installmentPrice.toFixed(2),
70
- };
71
- };
72
-
73
- export { calculateCardInstallment };
@@ -1,25 +0,0 @@
1
- type EnsureQuotesFunction = (rawValue: string) => string;
2
-
3
- /**
4
- * Ensures that a given rawValue string is enclosed in quotes.
5
- *
6
- * This function checks if the input string is already enclosed in either single
7
- * quotes (`'`) or double quotes (`"`). If the string is already quoted, it is
8
- * returned as-is. Otherwise, the function wraps the string in double quotes.
9
- *
10
- * @param url - The URL string to be checked and potentially quoted.
11
- * @returns The input string, either unchanged if it is already quoted, or wrapped in double quotes.
12
- */
13
-
14
- const ensureQuotes: EnsureQuotesFunction = (rawValue) => {
15
- const hasSingleQuotes = rawValue.startsWith("'") && rawValue.endsWith("'");
16
- const hasDoubleQuotes = rawValue.startsWith('"') && rawValue.endsWith('"');
17
-
18
- if (hasSingleQuotes || hasDoubleQuotes) {
19
- return rawValue;
20
- }
21
-
22
- return `"${rawValue}"`;
23
- };
24
-
25
- export { ensureQuotes };
@@ -1,68 +0,0 @@
1
- type MaskSensitiveDataFunction = (
2
- jsonString: string,
3
- sensitiveKeys?: string[]
4
- ) => string;
5
-
6
- /**
7
- * Masks sensitive data in a JSON string by replacing the values of specified keys with "****".
8
- *
9
- * @param jsonString - The JSON string to be processed.
10
- * @param sensitiveKeys - An array of keys whose values should be masked. Defaults to `["password", "confirmPassword", "creditCard"]`.
11
- * @returns A JSON string with sensitive data masked. If the input is not a valid JSON string, it returns the original string.
12
- *
13
- * @example
14
- * ```typescript
15
- * const jsonString = JSON.stringify({
16
- * username: "user123",
17
- * password: "secret",
18
- * profile: {
19
- * creditCard: "1234-5678-9012-3456",
20
- * },
21
- * });
22
- *
23
- * const result = maskSensitiveData(jsonString, ["password", "creditCard"]);
24
- * console.log(result);
25
- * // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
26
- * ```
27
- */
28
-
29
- const maskSensitiveData: MaskSensitiveDataFunction = (
30
- jsonString,
31
- sensitiveKeys = ["password", "confirmPassword", "creditCard"]
32
- ) => {
33
- function maskValue(key: string, value: any): any {
34
- if (sensitiveKeys.includes(key)) return "****";
35
- return value;
36
- }
37
-
38
- function recursiveMask(obj: any): any {
39
- if (Array.isArray(obj)) {
40
- return obj.map((item) => recursiveMask(item));
41
- } else if (obj !== null && typeof obj === "object") {
42
- return Object.keys(obj).reduce((acc, key) => {
43
- let value = obj[key];
44
- if (typeof value === "string") {
45
- try {
46
- const parsedValue = JSON.parse(value);
47
- if (typeof parsedValue === "object") {
48
- value = JSON.stringify(recursiveMask(parsedValue));
49
- }
50
- } catch (e) {}
51
- }
52
- acc[key] = recursiveMask(maskValue(key, value));
53
- return acc;
54
- }, {} as any);
55
- }
56
- return obj;
57
- }
58
-
59
- try {
60
- const jsonObject = JSON.parse(jsonString);
61
- const maskedObject = recursiveMask(jsonObject);
62
- return JSON.stringify(maskedObject);
63
- } catch (error) {
64
- return jsonString;
65
- }
66
- };
67
-
68
- export { maskSensitiveData };
@@ -1,29 +0,0 @@
1
- type RemoveCurrencySymbolsFunction = (formattedValue: string) => string;
2
-
3
- /**
4
- * Removes currency symbols from a given formatted string.
5
- *
6
- * This function takes a string that may contain currency symbols
7
- * and removes them using a regular expression. The resulting string
8
- * is also trimmed of any leading or trailing whitespace.
9
- *
10
- * @param formattedValue - The input string containing currency symbols.
11
- * @returns A string with all currency symbols removed and trimmed of whitespace.
12
- *
13
- * @example
14
- * removeCurrencySymbols("R$13,45"); // "13,45"
15
- * removeCurrencySymbols("$123.45"); // "123.45"
16
- * removeCurrencySymbols("€99.99"); // "99.99"
17
- * removeCurrencySymbols("¥1,000"); // "1,000"
18
- * removeCurrencySymbols("123.45"); // "123.45" (no symbols to remove)
19
- */
20
-
21
- const removeCurrencySymbols: RemoveCurrencySymbolsFunction = (
22
- formattedValue
23
- ) => {
24
- return formattedValue
25
- .replace(/(?:R\$|\p{Sc}|[$€¥£])/gu, "") // Inclui "R$" e outros símbolos comuns
26
- .trim();
27
- };
28
-
29
- export { removeCurrencySymbols };
@@ -1,20 +0,0 @@
1
- type RemoveNonNumericFunction = (formattedValue: string) => string;
2
-
3
- /**
4
- * Removes all non-numeric characters from a given string.
5
- *
6
- * @param prop - The input string from which non-numeric characters will be removed.
7
- * @returns A new string containing only numeric characters from the input.
8
- *
9
- * @example
10
- * ```typescript
11
- * const result = removeNonNumeric("abc123def456");
12
- * console.log(result); // Output: "123456"
13
- * ```
14
- */
15
-
16
- const removeNonNumeric: RemoveNonNumericFunction = (prop) => {
17
- return prop.replace(/[^0-9]/g, "");
18
- };
19
-
20
- export { removeNonNumeric };
@@ -1,20 +0,0 @@
1
- type StripHtmlTagsFunction = (rawHtml: string) => string;
2
-
3
- /**
4
- * Strips HTML tags from a string.
5
- *
6
- * This function removes all HTML tags from the provided string by replacing any content
7
- * that matches the HTML tag pattern with an empty string.
8
- *
9
- * @param rawHtml - The HTML string to be processed
10
- * @returns The input string with all HTML tags removed
11
- *
12
- * @example
13
- * stripHtmlTags("<p>Hello <strong>World</strong></p>"); // "Hello World"
14
- */
15
-
16
- const stripHtmlTags: StripHtmlTagsFunction = (rawHtml) => {
17
- return rawHtml.replace(/<\/?[^>]+(>|$)/g, "");
18
- };
19
-
20
- export { stripHtmlTags };
@@ -1,69 +0,0 @@
1
- type TruncateLargeFieldsFunction = (
2
- jsonString: string,
3
- maxLength?: number
4
- ) => string;
5
-
6
- /**
7
- * Truncates large string fields in a JSON string to a specified maximum length.
8
- *
9
- * This function parses a JSON string, traverses its structure recursively, and truncates
10
- * any string fields that exceed the specified maximum length. If a string field is truncated,
11
- * it is replaced with a message indicating the original length of the field.
12
- *
13
- * @param jsonString - The JSON string to process.
14
- * @param maxLength - The maximum allowed length for string fields. Defaults to 1000.
15
- * @returns A JSON string with large string fields truncated.
16
- *
17
- * @throws {Error} Throws an error if the input is not a valid JSON string.
18
- *
19
- * @example
20
- * ```typescript
21
- * const json = JSON.stringify({
22
- * name: "John",
23
- * description: "A very long description that exceeds the maximum length...",
24
- * nested: {
25
- * details: "Another long string that needs truncation."
26
- * }
27
- * });
28
- *
29
- * const result = truncateLargeFields(json, 50);
30
- * console.log(result);
31
- * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
32
- * ```
33
- */
34
-
35
- const truncateLargeFields: TruncateLargeFieldsFunction = (
36
- jsonString,
37
- maxLength = 1000
38
- ) => {
39
- function truncateValue(value: any): any {
40
- if (typeof value === "string" && value.length > maxLength) {
41
- return `To large information: field as ${value.length} characters`;
42
- }
43
- return value;
44
- }
45
-
46
- function recursiveTruncate(obj: any): any {
47
- if (Array.isArray(obj)) {
48
- return obj.map((item) => recursiveTruncate(item)); // Corrigido para processar elementos do array
49
- } else if (obj !== null && typeof obj === "object") {
50
- return Object.fromEntries(
51
- Object.entries(obj).map(([key, value]) => [
52
- key,
53
- recursiveTruncate(value), // Corrigido para aplicar recursão corretamente
54
- ])
55
- );
56
- }
57
- return truncateValue(obj); // Corrigido para truncar valores diretamente
58
- }
59
-
60
- try {
61
- const parsedJson = JSON.parse(jsonString);
62
- const truncatedJson = recursiveTruncate(parsedJson);
63
- return JSON.stringify(truncatedJson);
64
- } catch (error) {
65
- throw new Error("Invalid JSON string");
66
- }
67
- };
68
-
69
- export { truncateLargeFields };
@@ -1,41 +0,0 @@
1
- import { removeNonNumeric } from "../services/removeNonNumeric";
2
-
3
- type ValidateCepFunction = (rawCep: string) => boolean;
4
-
5
- /**
6
- * Removes all non-digit characters from the CEP.
7
- * @param cep - Raw CEP string.
8
- * @returns Only numeric characters.
9
- */
10
-
11
- /**
12
- * Validates a Brazilian CEP (Código de Endereçamento Postal).
13
- *
14
- * A valid CEP has 8 numeric digits.
15
- *
16
- * @param rawCep - CEP string, may include formatting (e.g., "12345-678").
17
- * @returns `true` if the CEP is valid, otherwise `false`.
18
- *
19
- * @example
20
- * ```ts
21
- * validateCep("12345-678"); // true
22
- * validateCep("12345678"); // true
23
- * validateCep("ABCDE-123"); // false
24
- * ```
25
- */
26
-
27
- const validateCep: ValidateCepFunction = (rawCep) => {
28
- if (!rawCep) return false;
29
-
30
- const validFormat = /^[0-9-]+$/.test(rawCep);
31
- if (!validFormat) return false;
32
-
33
- const cep = removeNonNumeric(rawCep);
34
-
35
- const CEP_LENGTH = 8;
36
- const isOnlyDigits = /^\d{8}$/.test(cep);
37
-
38
- return cep.length === CEP_LENGTH && isOnlyDigits;
39
- };
40
-
41
- export { validateCep };
@@ -1,65 +0,0 @@
1
- import { removeNonNumeric } from "../services/removeNonNumeric";
2
-
3
- type ValidateCnpjFunction = (rawCnpj: string) => boolean;
4
-
5
- function isInvalidLength(cnpj: string) {
6
- const CNPJ_LENGTH = 14;
7
- return cnpj.length !== CNPJ_LENGTH;
8
- }
9
-
10
- function hasAllDigitsEqual(cnpj: string) {
11
- const [firstDigit] = cnpj;
12
- return [...cnpj].every((digit) => digit === firstDigit);
13
- }
14
-
15
- function calculateDigit(cnpj: string, multipliers: number[]) {
16
- let total = 0;
17
- for (let i = 0; i < multipliers.length; i++) {
18
- total += parseInt(cnpj[i]) * multipliers[i];
19
- }
20
- const rest = total % 11;
21
- return rest < 2 ? 0 : 11 - rest;
22
- }
23
-
24
- function extractDigit(cnpj: string) {
25
- return cnpj.slice(12);
26
- }
27
-
28
- /**
29
- * Validates a Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) number.
30
- *
31
- * This function performs:
32
- * - Sanitization (removes non-digit characters).
33
- * - Length check (must be 14 digits).
34
- * - Repeating digits check (invalid if all digits are the same).
35
- * - Verifies the two check digits with the proper weights.
36
- *
37
- * @param rawCnpj - CNPJ string, possibly formatted.
38
- * @returns `true` if valid, otherwise `false`.
39
- *
40
- * @example
41
- * ```ts
42
- * validateCnpj("12.345.678/0001-95"); // false
43
- * validateCnpj("11.444.777/0001-61"); // true
44
- * ```
45
- */
46
-
47
- const validateCnpj: ValidateCnpjFunction = (rawCnpj) => {
48
- if (!rawCnpj) return false;
49
-
50
- const cnpj = removeNonNumeric(rawCnpj);
51
-
52
- if (isInvalidLength(cnpj)) return false;
53
- if (hasAllDigitsEqual(cnpj)) return false;
54
-
55
- const base = cnpj.slice(0, 12);
56
- const digit1 = calculateDigit(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]);
57
- const digit2 = calculateDigit(
58
- base + digit1,
59
- [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
60
- );
61
-
62
- return extractDigit(cnpj) === `${digit1}${digit2}`;
63
- };
64
-
65
- export { validateCnpj };
@@ -1,62 +0,0 @@
1
- import { removeNonNumeric } from "../services/removeNonNumeric";
2
-
3
- type ValidateCpfFunction = (rawCpf: string) => boolean;
4
-
5
- function isInvalidLength(cpf: string) {
6
- const CPF_LENGTH = 11;
7
- return cpf.length !== CPF_LENGTH;
8
- }
9
-
10
- function hasAllDigitsEqual(cpf: string) {
11
- const [firstCpfDigit] = cpf;
12
- return [...cpf].every((digit) => digit === firstCpfDigit);
13
- }
14
-
15
- function calculateDigit(cpf: string, factor: number) {
16
- let total = 0;
17
- for (const digit of cpf) {
18
- if (factor > 1) total += parseInt(digit) * factor--;
19
- }
20
- const rest = total % 11;
21
- return rest < 2 ? 0 : 11 - rest;
22
- }
23
-
24
- function extractDigit(cpf: string) {
25
- return cpf.slice(9);
26
- }
27
-
28
- /**
29
- * Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
30
- *
31
- * The CPF is a unique identifier assigned to Brazilian citizens and residents.
32
- * This function checks if the provided CPF is valid by performing the following steps:
33
- * - Removes any non-digit characters from the input.
34
- * - Verifies if the CPF has the correct length (11 digits).
35
- * - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
36
- * - Calculates the first and second verification digits using the CPF algorithm.
37
- * - Compares the calculated verification digits with the ones provided in the CPF.
38
- *
39
- * @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
40
- * @returns `true` if the CPF is valid, otherwise `false`.
41
- *
42
- * @example
43
- * ```typescript
44
- * validateCpf("123.456.789-09"); // false
45
- * validateCpf("111.444.777-35"); // true
46
- * ```
47
- */
48
-
49
- const validateCpf: ValidateCpfFunction = (rawCpf) => {
50
- if (!rawCpf) return false;
51
- const cpf = removeNonNumeric(rawCpf);
52
-
53
- if (isInvalidLength(cpf)) return false;
54
- if (hasAllDigitsEqual(cpf)) return false;
55
-
56
- const digit1 = calculateDigit(cpf, 10);
57
- const digit2 = calculateDigit(cpf, 11);
58
-
59
- return extractDigit(cpf) === `${digit1}${digit2}`;
60
- };
61
-
62
- export { validateCpf };
@@ -1,86 +0,0 @@
1
- type ValidateDateConfig = {
2
- inputFormat?: "DD/MM/YYYY" | "MM-DD-YYYY" | "YYYY-MM-DD";
3
- minYear?: number;
4
- maxYear?: number;
5
- };
6
-
7
- type ValidateDateFunction = (
8
- rawDate: string,
9
- config?: ValidateDateConfig
10
- ) => boolean;
11
-
12
- /**
13
- * Validates a date string based on the provided format and configuration.
14
- *
15
- * @param rawDate - The date string to validate.
16
- * @param config - Optional configuration object to customize validation.
17
- * @param config.inputFormat - The expected format of the input date.
18
- * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
19
- * Defaults to "DD/MM/YYYY".
20
- * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
21
- * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
22
- *
23
- * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
24
- *
25
- * @throws {Error} If an invalid date format is provided in the configuration.
26
- *
27
- * @example
28
- * ```typescript
29
- * validateDate("31/12/2023"); // true
30
- * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
31
- * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
32
- * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
33
- * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
34
- * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
35
- * ```
36
- */
37
-
38
- const validateDate: ValidateDateFunction = (rawDate, config) => {
39
- let day: string, month: string, year: string;
40
-
41
- const inputFormat = config?.inputFormat || "DD/MM/YYYY";
42
- const minYear = config?.minYear || 1900;
43
- const maxYear = config?.maxYear || 3000;
44
-
45
- if (inputFormat === "DD/MM/YYYY") {
46
- const dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
47
- if (!dateRegex.test(rawDate)) return false;
48
- [, day, month, year] = rawDate.match(dateRegex) || [];
49
- } else if (inputFormat === "MM-DD-YYYY") {
50
- const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
51
- if (!dateRegex.test(rawDate)) return false;
52
- [, month, day, year] = rawDate.match(dateRegex) || [];
53
- } else if (inputFormat === "YYYY-MM-DD") {
54
- const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
55
- if (!dateRegex.test(rawDate)) return false;
56
- [, year, month, day] = rawDate.match(dateRegex) || [];
57
- } else {
58
- throw new Error("Invalid date format");
59
- }
60
-
61
- const dayNum = parseInt(day, 10);
62
- const monthNum = parseInt(month, 10);
63
- const yearNum = parseInt(year, 10);
64
-
65
- if (dayNum < 1 || dayNum > 31) return false;
66
- if (monthNum < 1 || monthNum > 12) return false;
67
-
68
- const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
69
-
70
- if (monthNum === 2) {
71
- const isLeapYear =
72
- (yearNum % 4 === 0 && yearNum % 100 !== 0) || yearNum % 400 === 0;
73
- if (dayNum > (isLeapYear ? 29 : 28)) return false;
74
- } else if (dayNum > daysInMonth[monthNum - 1]) {
75
- return false;
76
- }
77
-
78
- if (yearNum < minYear || yearNum > maxYear) return false;
79
-
80
- const isValidDate =
81
- new Date(yearNum, monthNum - 1, dayNum).getDate() === dayNum;
82
-
83
- return isValidDate;
84
- };
85
-
86
- export { validateDate };
@@ -1,41 +0,0 @@
1
- type ValidatePasswordFunction = (rawPassword: string) => boolean;
2
-
3
- /**
4
- * Validates a password based on the following rules:
5
- * - At least 8 characters
6
- * - At least 1 uppercase letter
7
- * - At least 1 letter (any case)
8
- * - At least 1 number
9
- * - At least 1 special character
10
- *
11
- * @param rawPassword - The raw password string.
12
- * @returns `true` if password is valid, otherwise `false`.
13
- *
14
- * @example
15
- * ```ts
16
- * validatePassword("Senha@123"); // true
17
- * validatePassword("senha123"); // false (no uppercase, no special char)
18
- * ```
19
- */
20
-
21
- const validatePassword: ValidatePasswordFunction = (rawPassword) => {
22
- if (!rawPassword) return false;
23
-
24
- const hasMinLength = rawPassword.length >= 8;
25
- const hasUppercase = /[A-Z]/.test(rawPassword);
26
- const hasLetter = /[a-z]/.test(rawPassword);
27
- const hasNumber = /\d/.test(rawPassword);
28
- const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>_\-+=~`[\]\\\/]/.test(
29
- rawPassword
30
- );
31
-
32
- return [
33
- hasMinLength,
34
- hasUppercase,
35
- hasLetter,
36
- hasNumber,
37
- hasSpecialChar,
38
- ].every((condition) => condition);
39
- };
40
-
41
- export { validatePassword };
@@ -1,50 +0,0 @@
1
- import { countries } from "@arkyn/templates";
2
-
3
- type ValidatePhoneFunction = (rawPhone: string) => boolean;
4
-
5
- /**
6
- * Validates a phone number against a list of country-specific formats.
7
- *
8
- * The function iterates through a predefined list of countries and checks if the
9
- * provided phone number matches the format for any of the countries. It uses
10
- * regular expressions to validate the phone number based on the country's code,
11
- * prefix, and mask.
12
- *
13
- * Special handling is applied for Brazilian phone numbers (ISO code "BR"), which
14
- * allows for an optional ninth digit.
15
- *
16
- * @param rawPhone - The phone number to validate as a string.
17
- * @returns `true` if the phone number matches any country's format, otherwise `false`.
18
- *
19
- * @example
20
- * ```typescript
21
- * import { validatePhone } from "./validatePhone";
22
- *
23
- * validatePhone("+55 32912345678"); // true for a valid Brazilian phone number
24
- * validatePhone("+55 3212345678"); // true for a valid Brazilian phone number
25
- * validatePhone("+1-684 1234567"); // true for a valid American Samoa phone number
26
- * validatePhone("+5532912345678"); // false for an invalid Brazilian phone number
27
- * validatePhone("+55 1234567890"); // false for an invalid Brazilian phone number
28
- * ```
29
- */
30
-
31
- const validatePhone: ValidatePhoneFunction = (rawPhone) => {
32
- for (const country of countries) {
33
- const countryCode = country.code;
34
- const prefix = country.prefix ? `-${country.prefix}` : "";
35
- const digitCount = country.mask.replace(/[^_]/g, "").length;
36
-
37
- if (country.iso === "BR") {
38
- const brazilRegex = new RegExp(`^\\${countryCode} \\d{2}9?\\d{8}$`);
39
- if (brazilRegex.test(rawPhone)) return true;
40
- continue;
41
- }
42
-
43
- const regex = new RegExp(`^\\${countryCode}${prefix} \\d{${digitCount}}$`);
44
- if (regex.test(rawPhone)) return true;
45
- }
46
-
47
- return false;
48
- };
49
-
50
- export { validatePhone };