@senior-agronegocio/angular-components 0.0.52 → 0.0.56

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.
@@ -34,149 +34,6 @@ var DateComparisonType;
34
34
  DateComparisonType["lessThan"] = "lessThan";
35
35
  })(DateComparisonType || (DateComparisonType = {}));
36
36
 
37
- const AGRO_REGEX = {
38
- /**
39
- * Validação de E-mail
40
- */
41
- isEmail: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
42
- /**
43
- * Validação de Números Inteiros Positivos
44
- */
45
- positiveInteger: /^[1-9]\d*$/,
46
- /**
47
- * Validação de Números Decimais Positivos
48
- */
49
- positiveDecimal: /^\d*\.?\d+$/,
50
- /**
51
- * Validação de string que consiste apenas em espaços em branco ou está vazia.
52
- */
53
- onlyBlankSpaces: /^\s*$/,
54
- /**
55
- * Validação de CEP (Código Postal)
56
- */
57
- zipCode: /^\d{8}$|^\d{5}-\d{3}$/,
58
- /**
59
- * Validação de String (qualquer caractere)
60
- */
61
- isString: /^[\s\S]*$/,
62
- /**
63
- * Validação de UUID
64
- */
65
- isUUID: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/,
66
- /**
67
- * Validação de Número
68
- */
69
- isNumber: /^-?\d+$/,
70
- /**
71
- * Validação de Número Decimal
72
- */
73
- isDecimal: /^\d*\.?\d+$/,
74
- /**
75
- * Validação de Placa de Veículo
76
- */
77
- isLicensePlate: /^[A-Za-z0-9]{1,7}-?[A-Za-z0-9]{1,7}$/,
78
- /**
79
- * Validação de Número de Telefone
80
- */
81
- isPhoneNumber: /^\+?\d{1,4}-?\d{6,11}$/,
82
- /**
83
- * Validação de Data (Formato YYYY-MM-DD)
84
- */
85
- isDate: /^\d{4}-\d{2}-\d{2}$/,
86
- /**
87
- * Validação de Hora (Formato HH:mm)
88
- */
89
- isTime: /^(0\d|1\d|2[0-3]):[0-5]\d$/,
90
- /**
91
- * Validação de Data e Hora (Formato YYYY-MM-DD HH:mm)
92
- */
93
- isDateTime: /^\d{4}-\d{2}-\d{2} (0\d|1\d|2[0-3]):[0-5]\d$/,
94
- /**
95
- * Validação de URL
96
- */
97
- isURL: /^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/,
98
- /**
99
- * Validação de Número Hexadecimal
100
- */
101
- isHexNumber: /^[0-9a-fA-F]+$/,
102
- /**
103
- * Validação de Base64
104
- */
105
- isBase64: /^[a-zA-Z0-9+/]+={0,2}$/,
106
- /**
107
- * Validação de Nome de Usuário (3 a 20 caracteres alfanuméricos)
108
- */
109
- isUsername: /^\w{3,20}$/,
110
- /**
111
- * Validação de Alfanumérico
112
- */
113
- isAlphanumeric: /^[a-zA-Z0-9]+$/,
114
- /**
115
- * Validação de Slug (letras minúsculas, números e traços)
116
- */
117
- isSlug: /^[a-z0-9-]+$/,
118
- /**
119
- * Validação de Número de Cartão de Crédito
120
- */
121
- isCreditCard: /^\d{4}-\d{4}-\d{4}-\d{4}$/,
122
- /**
123
- * Validação de Número Hexadecimal
124
- */
125
- isHexadecimal: /^[0-9a-fA-F]+$/,
126
- /**
127
- * Validação de Moeda
128
- */
129
- isCurrency: /^\d+(\.\d{1,2})?$/,
130
- /**
131
- * Validação de Porcentagem
132
- */
133
- isPercentage: /^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/,
134
- /**
135
- * Validação de Tag HTML Simples
136
- */
137
- isHTMLTag: /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/,
138
- /**
139
- * Validação de Nome de Usuário com Espaços (3 a 20 caracteres alfanuméricos e espaços)
140
- */
141
- isUsernameWithSpaces: /^[a-zA-Z0-9_ ]{3,20}$/,
142
- /**
143
- * Validação de Senha Forte (mínimo 8 caracteres, uma letra minúscula, uma letra maiúscula, um número e um caractere especial)
144
- */
145
- isStrongPassword: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
146
- /**
147
- * Validação de String Alfabética
148
- */
149
- isAlphabetic: /^[a-zA-Z]+$/,
150
- /**
151
- * Validação de Hora no Formato de 12 Horas
152
- */
153
- isTime12Hour: /^(0?[1-9]|1[0-2]):\d{2} (AM|PM)$/i,
154
- /**
155
- * Validação de Latitude
156
- */
157
- isLatitude: /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)$/,
158
- /**
159
- * Validação de Longitude
160
- */
161
- isLongitude: /^[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/,
162
- /**
163
- * Validação de Endereço MAC
164
- */
165
- isMACAddress: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
166
- /**
167
- * Validação de Data de Expiração de Cartão de Crédito
168
- */
169
- isCreditCardExpiration: /^(0[1-9]|1[0-2])\/\d{2}$/,
170
- /**
171
- * Validação de Número de Seguro Social (SSN)
172
- */
173
- isSSN: /^\d{3}-\d{2}-\d{4}$/,
174
- /**
175
- * Validação se todos os dígitos são iguais
176
- */
177
- isAllDigitsEqual: /^(.)\1+$/,
178
- };
179
-
180
37
  var NumberComparisonType;
181
38
  (function (NumberComparisonType) {
182
39
  NumberComparisonType["EQUALS"] = "EQUALS";
@@ -1521,277 +1378,52 @@ class AgroObjectUtils {
1521
1378
  }
1522
1379
  }
1523
1380
 
1524
- class AgroFormValidator {
1525
- /**
1526
- * Validator para checar se o campo é um e-mail
1527
- *
1528
- * @example
1529
- * this.myForm = this.fb.group({
1530
- * EMAIL_FIELD: ['', [Validators.required, AgroFormValidator.emailValidator]]
1531
- * });
1532
- * @param control
1533
- * @returns
1534
- */
1535
- static emailValidator(control) {
1536
- if (control.value && !AGRO_REGEX.isEmail.test(control.value)) {
1537
- control.setErrors({ emailValidator: true });
1538
- return { emailValidator: true };
1381
+ class AgroCookieUtils {
1382
+ static getCookie(name, parseURIValue = false) {
1383
+ const cookieValue = document.cookie.split(';')
1384
+ .map(cookie => cookie.trim())
1385
+ .find(cookie => cookie.startsWith(name));
1386
+ let result = cookieValue === null || cookieValue === void 0 ? void 0 : cookieValue.split('=')[1];
1387
+ if (parseURIValue && result) {
1388
+ result = decodeURIComponent(result);
1539
1389
  }
1540
- control.setErrors(null);
1541
- return null;
1390
+ return result;
1391
+ }
1392
+ static parseCookieToObject(cookieString, parseURIString = false) {
1393
+ const cookieObject = {};
1394
+ if (parseURIString) {
1395
+ cookieString = decodeURIComponent(cookieString);
1396
+ }
1397
+ cookieString.split(';').forEach(cookie => {
1398
+ const [key, value] = cookie.split('=').map(c => c.trim());
1399
+ cookieObject[key] = value;
1400
+ });
1401
+ return cookieObject;
1542
1402
  }
1403
+ setCookie(name, value, days) {
1404
+ const date = new Date();
1405
+ date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
1406
+ const expires = 'expires=' + date.toUTCString();
1407
+ document.cookie = name + '=' + value + ';' + expires + ';path=/';
1408
+ }
1409
+ }
1410
+
1411
+ class AgroDateUtils {
1543
1412
  /**
1544
- * Aplique esse validador em um campo do tipo Date, para verificar se a data selecionada é maior ou menor que a data atual.
1545
- *
1546
- * Utilize o parâmetro comparisonType para definir se a data selecionada deve ser maior ou menor que a data atual.
1547
- * A validação será através do enum DateComparisonType.
1548
- *
1549
- * @example
1550
- * this.myForm = this.fb.group({
1551
- * NOME_CAMPO: ['', [Validators.required, AgroFormValidator.compareDateWithToday(DateComparisonType.greatherThan)]]
1552
- * });
1553
- * @param comparisonType
1554
- * @returns
1413
+ * Verifica se uma data é nula ou indefinida.
1414
+ * @param date - A data a ser verificada.
1415
+ * @returns True se a data for nula ou indefinida, false caso contrário.
1555
1416
  */
1556
- static compareDateWithToday(comparisonType) {
1557
- const compareDate = (control) => {
1558
- const methodName = 'dateComparisonToday';
1559
- const selectedDate = new Date(control.value);
1560
- const currentDate = new Date();
1561
- const conditions = {
1562
- [DateComparisonType.greatherThan]: selectedDate <= currentDate,
1563
- [DateComparisonType.lessThan]: selectedDate >= currentDate
1564
- };
1565
- if (conditions[comparisonType]) {
1566
- return { [methodName]: { value: control.value } };
1567
- }
1568
- return null;
1569
- };
1570
- return compareDate;
1417
+ static isNullOrUndefined(date) {
1418
+ return date === null || date === undefined;
1571
1419
  }
1572
1420
  /**
1573
- * Compara dois campos do tipo Date, verificando se o campo A é maior que o campo B. Se A for maior que B, então
1574
- * o campo A é invalidado. Caso contrário, o campo A é validado.
1575
- *
1576
- * Aplique esse campo no FormGroup, passando os nomes dos campos que deseja comparar.
1577
- * @example
1578
- * this.myForm = this.fb.group({
1579
- NOME_CAMPO_dateA: ['', Validators.required],
1580
- NOME_CAMPO_dateB: ['', Validators.required]
1581
- }, { validator: AgroFormValidator.dateComparisonValidator('NOME_CAMPO_dateA', 'NOME_CAMPO_dateB') });
1582
- * @param controlNameA
1583
- * @param controlNameB
1584
- * @returns
1421
+ * Verifica se uma data não é nula e não é indefinida.
1422
+ * @param date - A data a ser verificada.
1423
+ * @returns True se a data não for nula e não for indefinida, false caso contrário.
1585
1424
  */
1586
- static compareDateWithOtherDateField(controlNameA, controlNameB) {
1587
- const compareDate = (control) => {
1588
- var _a, _b, _c, _d, _e;
1589
- const formGroup = control;
1590
- const dateA = (_a = formGroup.get(controlNameA)) === null || _a === void 0 ? void 0 : _a.value;
1591
- const dateB = (_b = formGroup.get(controlNameB)) === null || _b === void 0 ? void 0 : _b.value;
1592
- const methodName = 'compareDateWithOtherDateField';
1593
- if (dateA && dateB) {
1594
- const dateAObj = new Date(dateA);
1595
- const dateBObj = new Date(dateB);
1596
- if (dateAObj < dateBObj) {
1597
- (_c = formGroup.get(controlNameA)) === null || _c === void 0 ? void 0 : _c.setErrors({ [methodName]: true });
1598
- return { [methodName]: true };
1599
- }
1600
- else if ((_d = formGroup.get(controlNameA)) === null || _d === void 0 ? void 0 : _d.hasError(methodName)) {
1601
- (_e = formGroup.get(controlNameA)) === null || _e === void 0 ? void 0 : _e.setErrors(null);
1602
- }
1603
- }
1604
- return null;
1605
- };
1606
- return compareDate;
1607
- }
1608
- /**
1609
- * Validator para checar se o campo é um número de telefone de acordo com uma máscara informada.
1610
- *
1611
- * @example
1612
- * this.myForm = this.fb.group({
1613
- * TELEFONE_FIELD: ['', [Validators.required, AgroFormValidator.phoneValidator('(99) 9999-9999')]]
1614
- * });
1615
- * @param mask
1616
- * @returns
1617
- */
1618
- static phoneValidator(mask) {
1619
- const phoneControlValidation = (control) => {
1620
- const methodName = 'phoneValidator';
1621
- const regex = new RegExp(`^${mask.replace(/9/g, '\\d').replace(/\(/g, '\\(').replace(/\)/g, '\\)').replace(/-/g, '\\-')}$`);
1622
- if (control.value && !regex.test(control.value)) {
1623
- control.setErrors({ [methodName]: true });
1624
- return { [methodName]: true };
1625
- }
1626
- control.setErrors(null);
1627
- return null;
1628
- };
1629
- return phoneControlValidation;
1630
- }
1631
- /**
1632
- * Validator para checar se um campo de números é maior ou menor que outro campo.
1633
- *
1634
- * Aplique esse validator no FormGroup, passando os nomes dos campos que deseja comparar.
1635
- * @example
1636
- * this.myForm = this.fb.group({
1637
- * NUMERO_A: ['', Validators.required],
1638
- * NUMERO_B: ['', Validators.required]
1639
- * }, { validator: AgroFormValidator.compareNumberFields('NUMERO_A', 'NUMERO_B', NumberComparisonType.EQUALS) });
1640
- *
1641
- * Neste caso, a verificação será se o NUMERO_A é igual ao NUMERB_B.
1642
- * @param controlNameA
1643
- * @param controlNameB
1644
- * @returns
1645
- */
1646
- static compareNumberFields(controlNameA, controlNameB, comparisonMethod) {
1647
- const compareNumber = (control) => {
1648
- var _a, _b, _c;
1649
- const formGroup = control;
1650
- const numberA = (_a = formGroup.get(controlNameA)) === null || _a === void 0 ? void 0 : _a.value;
1651
- const numberB = (_b = formGroup.get(controlNameB)) === null || _b === void 0 ? void 0 : _b.value;
1652
- const methodName = 'compareNumberFields';
1653
- if (numberA && numberB) {
1654
- const errorType = NumberComparisonType[comparisonMethod];
1655
- const errorCondition = {
1656
- [NumberComparisonType.EQUALS]: numberA !== numberB,
1657
- [NumberComparisonType.GREATER_THAN]: numberA <= numberB,
1658
- [NumberComparisonType.LESS_THAN]: numberA >= numberB,
1659
- [NumberComparisonType.GREATER_THAN_OR_EQUAL]: numberA < numberB,
1660
- [NumberComparisonType.LESS_THAN_OR_EQUAL]: numberA > numberB,
1661
- [NumberComparisonType.NOT_EQUALS]: numberA === numberB
1662
- };
1663
- if (errorCondition[comparisonMethod]) {
1664
- const controlA = formGroup.get(controlNameA);
1665
- if (controlA) {
1666
- controlA.setErrors({ [methodName]: comparisonMethod });
1667
- }
1668
- return { [methodName]: errorType };
1669
- }
1670
- else if ((_c = formGroup.get(controlNameA)) === null || _c === void 0 ? void 0 : _c.hasError(methodName)) {
1671
- const controlA = formGroup.get(controlNameA);
1672
- if (controlA) {
1673
- controlA.setErrors(null);
1674
- }
1675
- }
1676
- }
1677
- return null;
1678
- };
1679
- return compareNumber;
1680
- }
1681
- /**
1682
- * Validator para checar se um valor está entre os demais valores de três formControls.
1683
- *
1684
- * Aplique esse validator no FormGroup, passando os nomes dos três formControls que deseja comparar.
1685
- * @example
1686
- * this.myForm = this.fb.group({
1687
- * minorFormControl: ['', Validators.required],
1688
- * targetFormControl: ['', Validators.required],
1689
- * majorFormControl: ['', Validators.required]
1690
- * }, { validator: AgroFormValidator.checkValueBetween('minorFormControl', 'targetFormControl', 'majorFormControl') });
1691
- *
1692
- * Neste caso, a verificação será se o targetFormControl está entre o minorFormControl e o majorFormControl.
1693
- * @param minorFormControl
1694
- * @param targetFormControl
1695
- * @param majorFormControl
1696
- * @returns
1697
- */
1698
- static checkValueBetween(minorFormControl, targetFormControl, majorFormControl) {
1699
- const checkValue = (control) => {
1700
- var _a, _b, _c, _d;
1701
- const formGroup = control;
1702
- const valueA = (_a = formGroup.get(minorFormControl)) === null || _a === void 0 ? void 0 : _a.value;
1703
- const valueB = (_b = formGroup.get(targetFormControl)) === null || _b === void 0 ? void 0 : _b.value;
1704
- const valueC = (_c = formGroup.get(majorFormControl)) === null || _c === void 0 ? void 0 : _c.value;
1705
- const methodName = 'checkValueBetween';
1706
- if (valueA && valueB && valueC) {
1707
- if (valueB < valueA || valueB > valueC) {
1708
- const targetControl = formGroup.get(targetFormControl);
1709
- if (targetControl) {
1710
- targetControl.setErrors({ [methodName]: true });
1711
- }
1712
- return { [methodName]: true };
1713
- }
1714
- else if ((_d = formGroup.get(targetFormControl)) === null || _d === void 0 ? void 0 : _d.hasError(methodName)) {
1715
- const targetControl = formGroup.get(targetFormControl);
1716
- if (targetControl) {
1717
- targetControl.setErrors(null);
1718
- }
1719
- }
1720
- }
1721
- return null;
1722
- };
1723
- return checkValue;
1724
- }
1725
- /**
1726
- * Validator para checar se o campo é um objeto e se possui uma propriedade específica.
1727
- *
1728
- * @example
1729
- * this.myForm = this.fb.group({
1730
- * OBJETO_FIELD: ['', [Validators.required, AgroFormValidator.objectPropertyValidator('propriedade')]]
1731
- * });
1732
- * @param propertyName
1733
- * @returns
1734
- */
1735
- static objectPropertyValidator(propertyName) {
1736
- const objectProperty = (control) => {
1737
- const methodName = 'objectProperty';
1738
- if (AgroObjectUtils.isObject(control.value) && AgroObjectUtils.containsProperty(control.value, propertyName)) {
1739
- control.setErrors(null);
1740
- return null;
1741
- }
1742
- control.setErrors({ [methodName]: true });
1743
- return { [methodName]: true };
1744
- };
1745
- return objectProperty;
1746
- }
1747
- }
1748
-
1749
- class AgroCookieUtils {
1750
- static getCookie(name, parseURIValue = false) {
1751
- const cookieValue = document.cookie.split(';')
1752
- .map(cookie => cookie.trim())
1753
- .find(cookie => cookie.startsWith(name));
1754
- let result = cookieValue === null || cookieValue === void 0 ? void 0 : cookieValue.split('=')[1];
1755
- if (parseURIValue && result) {
1756
- result = decodeURIComponent(result);
1757
- }
1758
- return result;
1759
- }
1760
- static parseCookieToObject(cookieString, parseURIString = false) {
1761
- const cookieObject = {};
1762
- if (parseURIString) {
1763
- cookieString = decodeURIComponent(cookieString);
1764
- }
1765
- cookieString.split(';').forEach(cookie => {
1766
- const [key, value] = cookie.split('=').map(c => c.trim());
1767
- cookieObject[key] = value;
1768
- });
1769
- return cookieObject;
1770
- }
1771
- setCookie(name, value, days) {
1772
- const date = new Date();
1773
- date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
1774
- const expires = 'expires=' + date.toUTCString();
1775
- document.cookie = name + '=' + value + ';' + expires + ';path=/';
1776
- }
1777
- }
1778
-
1779
- class AgroDateUtils {
1780
- /**
1781
- * Verifica se uma data é nula ou indefinida.
1782
- * @param date - A data a ser verificada.
1783
- * @returns True se a data for nula ou indefinida, false caso contrário.
1784
- */
1785
- static isNullOrUndefined(date) {
1786
- return date === null || date === undefined;
1787
- }
1788
- /**
1789
- * Verifica se uma data não é nula e não é indefinida.
1790
- * @param date - A data a ser verificada.
1791
- * @returns True se a data não for nula e não for indefinida, false caso contrário.
1792
- */
1793
- static isNotNullOrUndefined(date) {
1794
- return !AgroDateUtils.isNullOrUndefined(date);
1425
+ static isNotNullOrUndefined(date) {
1426
+ return !AgroDateUtils.isNullOrUndefined(date);
1795
1427
  }
1796
1428
  /**
1797
1429
  * Verifica se uma data é válida.
@@ -1860,37 +1492,180 @@ class AgroDateUtils {
1860
1492
  * @param otherDate - A outra data a ser comparada.
1861
1493
  * @returns True se a data for menor que outra data, false caso contrário.
1862
1494
  */
1863
- static isLess(date, otherDate) {
1864
- return date < otherDate;
1865
- }
1495
+ static isLess(date, otherDate) {
1496
+ return date < otherDate;
1497
+ }
1498
+ /**
1499
+ * Verifica se uma data é maior que outra data.
1500
+ * @param date - A data a ser verificada.
1501
+ * @param otherDate - A outra data a ser comparada.
1502
+ * @returns True se a data for maior que outra data, false caso contrário.
1503
+ */
1504
+ static isGreater(date, otherDate) {
1505
+ return date > otherDate;
1506
+ }
1507
+ /**
1508
+ * Retorna a data formatada conforme o formato especificado.
1509
+ * @param date
1510
+ * @param format
1511
+ * @returns
1512
+ */
1513
+ static formatDate(date, format = 'DD/MM/YYYY') {
1514
+ const moment$1 = moment;
1515
+ return moment$1(date).utc().format(format);
1516
+ }
1517
+ /**
1518
+ * Retorna uma string com o número informado adicionando um 0 à esquerda, caso o número seja menor que 10.
1519
+ * @param value
1520
+ * @returns
1521
+ */
1522
+ static padZero(value) {
1523
+ return value < AGRO_NUMBERS.TEN ? '0' + value : value.toString();
1524
+ }
1525
+ }
1526
+
1527
+ const AGRO_REGEX = {
1528
+ /**
1529
+ * Validação de E-mail
1530
+ */
1531
+ isEmail: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
1532
+ /**
1533
+ * Validação de Números Inteiros Positivos
1534
+ */
1535
+ positiveInteger: /^[1-9]\d*$/,
1536
+ /**
1537
+ * Validação de Números Decimais Positivos
1538
+ */
1539
+ positiveDecimal: /^\d*\.?\d+$/,
1540
+ /**
1541
+ * Validação de string que consiste apenas em espaços em branco ou está vazia.
1542
+ */
1543
+ onlyBlankSpaces: /^\s*$/,
1544
+ /**
1545
+ * Validação de CEP (Código Postal)
1546
+ */
1547
+ zipCode: /^\d{8}$|^\d{5}-\d{3}$/,
1548
+ /**
1549
+ * Validação de String (qualquer caractere)
1550
+ */
1551
+ isString: /^[\s\S]*$/,
1552
+ /**
1553
+ * Validação de UUID
1554
+ */
1555
+ isUUID: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/,
1556
+ /**
1557
+ * Validação de Número
1558
+ */
1559
+ isNumber: /^-?\d+$/,
1560
+ /**
1561
+ * Validação de Número Decimal
1562
+ */
1563
+ isDecimal: /^\d*\.?\d+$/,
1564
+ /**
1565
+ * Validação de Placa de Veículo
1566
+ */
1567
+ isLicensePlate: /^[A-Za-z0-9]{1,7}-?[A-Za-z0-9]{1,7}$/,
1568
+ /**
1569
+ * Validação de Número de Telefone
1570
+ */
1571
+ isPhoneNumber: /^\+?\d{1,4}-?\d{6,11}$/,
1572
+ /**
1573
+ * Validação de Data (Formato YYYY-MM-DD)
1574
+ */
1575
+ isDate: /^\d{4}-\d{2}-\d{2}$/,
1576
+ /**
1577
+ * Validação de Hora (Formato HH:mm)
1578
+ */
1579
+ isTime: /^(0\d|1\d|2[0-3]):[0-5]\d$/,
1580
+ /**
1581
+ * Validação de Data e Hora (Formato YYYY-MM-DD HH:mm)
1582
+ */
1583
+ isDateTime: /^\d{4}-\d{2}-\d{2} (0\d|1\d|2[0-3]):[0-5]\d$/,
1584
+ /**
1585
+ * Validação de URL
1586
+ */
1587
+ isURL: /^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/,
1588
+ /**
1589
+ * Validação de Número Hexadecimal
1590
+ */
1591
+ isHexNumber: /^[0-9a-fA-F]+$/,
1592
+ /**
1593
+ * Validação de Base64
1594
+ */
1595
+ isBase64: /^[a-zA-Z0-9+/]+={0,2}$/,
1596
+ /**
1597
+ * Validação de Nome de Usuário (3 a 20 caracteres alfanuméricos)
1598
+ */
1599
+ isUsername: /^\w{3,20}$/,
1600
+ /**
1601
+ * Validação de Alfanumérico
1602
+ */
1603
+ isAlphanumeric: /^[a-zA-Z0-9]+$/,
1604
+ /**
1605
+ * Validação de Slug (letras minúsculas, números e traços)
1606
+ */
1607
+ isSlug: /^[a-z0-9-]+$/,
1608
+ /**
1609
+ * Validação de Número de Cartão de Crédito
1610
+ */
1611
+ isCreditCard: /^\d{4}-\d{4}-\d{4}-\d{4}$/,
1612
+ /**
1613
+ * Validação de Número Hexadecimal
1614
+ */
1615
+ isHexadecimal: /^[0-9a-fA-F]+$/,
1616
+ /**
1617
+ * Validação de Moeda
1618
+ */
1619
+ isCurrency: /^\d+(\.\d{1,2})?$/,
1620
+ /**
1621
+ * Validação de Porcentagem
1622
+ */
1623
+ isPercentage: /^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/,
1624
+ /**
1625
+ * Validação de Tag HTML Simples
1626
+ */
1627
+ isHTMLTag: /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/,
1628
+ /**
1629
+ * Validação de Nome de Usuário com Espaços (3 a 20 caracteres alfanuméricos e espaços)
1630
+ */
1631
+ isUsernameWithSpaces: /^[a-zA-Z0-9_ ]{3,20}$/,
1632
+ /**
1633
+ * Validação de Senha Forte (mínimo 8 caracteres, uma letra minúscula, uma letra maiúscula, um número e um caractere especial)
1634
+ */
1635
+ isStrongPassword: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
1636
+ /**
1637
+ * Validação de String Alfabética
1638
+ */
1639
+ isAlphabetic: /^[a-zA-Z]+$/,
1640
+ /**
1641
+ * Validação de Hora no Formato de 12 Horas
1642
+ */
1643
+ isTime12Hour: /^(0?[1-9]|1[0-2]):\d{2} (AM|PM)$/i,
1644
+ /**
1645
+ * Validação de Latitude
1646
+ */
1647
+ isLatitude: /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)$/,
1648
+ /**
1649
+ * Validação de Longitude
1650
+ */
1651
+ isLongitude: /^[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/,
1866
1652
  /**
1867
- * Verifica se uma data é maior que outra data.
1868
- * @param date - A data a ser verificada.
1869
- * @param otherDate - A outra data a ser comparada.
1870
- * @returns True se a data for maior que outra data, false caso contrário.
1653
+ * Validação de Endereço MAC
1871
1654
  */
1872
- static isGreater(date, otherDate) {
1873
- return date > otherDate;
1874
- }
1655
+ isMACAddress: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
1875
1656
  /**
1876
- * Retorna a data formatada conforme o formato especificado.
1877
- * @param date
1878
- * @param format
1879
- * @returns
1657
+ * Validação de Data de Expiração de Cartão de Crédito
1880
1658
  */
1881
- static formatDate(date, format = 'DD/MM/YYYY') {
1882
- const moment$1 = moment;
1883
- return moment$1(date).utc().format(format);
1884
- }
1659
+ isCreditCardExpiration: /^(0[1-9]|1[0-2])\/\d{2}$/,
1885
1660
  /**
1886
- * Retorna uma string com o número informado adicionando um 0 à esquerda, caso o número seja menor que 10.
1887
- * @param value
1888
- * @returns
1661
+ * Validação de Número de Seguro Social (SSN)
1889
1662
  */
1890
- static padZero(value) {
1891
- return value < AGRO_NUMBERS.TEN ? '0' + value : value.toString();
1892
- }
1893
- }
1663
+ isSSN: /^\d{3}-\d{2}-\d{4}$/,
1664
+ /**
1665
+ * Validação se todos os dígitos são iguais
1666
+ */
1667
+ isAllDigitsEqual: /^(.)\1+$/,
1668
+ };
1894
1669
 
1895
1670
  /**
1896
1671
  * Classe utilitária para operações de string.
@@ -2154,23 +1929,19 @@ class AgroStringUtils {
2154
1929
  let remainder = sum % 11;
2155
1930
  return remainder < 2 ? 0 : 11 - remainder;
2156
1931
  };
2157
- return (calcCheckDigit(9) === Number(cpf[9]) &&
2158
- calcCheckDigit(10) === Number(cpf[10]));
1932
+ return calcCheckDigit(9) === Number(cpf[9]) && calcCheckDigit(10) === Number(cpf[10]);
2159
1933
  }
2160
1934
  static validateCNPJ(cnpj) {
2161
1935
  cnpj = cnpj.replace(/\D/g, "");
2162
1936
  if (cnpj.length !== 14 || /^(\d)\1{13}$/.test(cnpj))
2163
1937
  return false;
2164
1938
  const calcularDigito = (length) => {
2165
- const pesos = length === 12
2166
- ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
2167
- : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
1939
+ const pesos = length === 12 ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
2168
1940
  const soma = pesos.reduce((acc, peso, i) => acc + Number(cnpj[i]) * peso, 0);
2169
1941
  const resto = soma % 11;
2170
1942
  return resto < 2 ? 0 : 11 - resto;
2171
1943
  };
2172
- return (calcularDigito(12) === Number(cnpj[12]) &&
2173
- calcularDigito(13) === Number(cnpj[13]));
1944
+ return calcularDigito(12) === Number(cnpj[12]) && calcularDigito(13) === Number(cnpj[13]);
2174
1945
  }
2175
1946
  /**
2176
1947
  * Método para aplicar uma máscara em uma string. Considere a máscara com valores 9 para aplicação
@@ -2219,6 +1990,25 @@ class AgroStringUtils {
2219
1990
  static isInvalid(str) {
2220
1991
  return !AgroStringUtils.isValid(str);
2221
1992
  }
1993
+ /**
1994
+ * Valida se uma string é um e-mail válido ou não
1995
+ * Retorna um booleano para indicar se é um e-mail válido ou não
1996
+ * @param email - A string a ser verificada
1997
+ * @returns True se a string for um e-mail válido, false caso contrário
1998
+ */
1999
+ static isValidEmail(email) {
2000
+ return AGRO_REGEX.isEmail.test(email);
2001
+ }
2002
+ /**
2003
+ * Valida se uma string é uma placa de veículo BR válida ou não.
2004
+ * Retorna um booleano para indicar se é uma placa válida ou não.
2005
+ * @param plate - A string a ser verificada
2006
+ */
2007
+ static isValidLicensePlate(plate) {
2008
+ const oldFormat = /^[A-Z]{3}-?\d{4}$/;
2009
+ const mercosulFormat = /^[A-Z]{3}\d[A-Z]\d{2}$/;
2010
+ return oldFormat.test(plate) || mercosulFormat.test(plate);
2011
+ }
2222
2012
  }
2223
2013
 
2224
2014
  class AgroPlatformUtils {
@@ -2622,6 +2412,240 @@ class AgroArrayUtils {
2622
2412
  }
2623
2413
  }
2624
2414
 
2415
+ class AgroFormValidator {
2416
+ /**
2417
+ * Validator para checar se o campo é um e-mail
2418
+ *
2419
+ * @example
2420
+ * this.myForm = this.fb.group({
2421
+ * EMAIL_FIELD: ['', [Validators.required, AgroFormValidator.emailValidator]]
2422
+ * });
2423
+ * @param control
2424
+ * @returns
2425
+ */
2426
+ static emailValidator(control) {
2427
+ const email = control.value;
2428
+ if (!email) {
2429
+ return null;
2430
+ }
2431
+ return AgroStringUtils.isValidEmail(email) ? null : { emailValidator: true };
2432
+ }
2433
+ /**
2434
+ * Aplique esse validador em um campo do tipo Date, para verificar se a data selecionada é maior ou menor que a data atual.
2435
+ *
2436
+ * Utilize o parâmetro comparisonType para definir se a data selecionada deve ser maior ou menor que a data atual.
2437
+ * A validação será através do enum DateComparisonType.
2438
+ *
2439
+ * @example
2440
+ * this.myForm = this.fb.group({
2441
+ * NOME_CAMPO: ['', [Validators.required, AgroFormValidator.compareDateWithToday(DateComparisonType.greatherThan)]]
2442
+ * });
2443
+ * @param comparisonType
2444
+ * @returns
2445
+ */
2446
+ static compareDateWithToday(comparisonType) {
2447
+ const compareDate = (control) => {
2448
+ const methodName = 'dateComparisonToday';
2449
+ const selectedDate = new Date(control.value);
2450
+ const currentDate = new Date();
2451
+ const conditions = {
2452
+ [DateComparisonType.greatherThan]: selectedDate <= currentDate,
2453
+ [DateComparisonType.lessThan]: selectedDate >= currentDate
2454
+ };
2455
+ if (conditions[comparisonType]) {
2456
+ return { [methodName]: { value: control.value } };
2457
+ }
2458
+ return null;
2459
+ };
2460
+ return compareDate;
2461
+ }
2462
+ /**
2463
+ * Compara dois campos do tipo Date, verificando se o campo A é maior que o campo B. Se A for maior que B, então
2464
+ * o campo A é invalidado. Caso contrário, o campo A é validado.
2465
+ *
2466
+ * Aplique esse campo no FormGroup, passando os nomes dos campos que deseja comparar.
2467
+ * @example
2468
+ * this.myForm = this.fb.group({
2469
+ NOME_CAMPO_dateA: ['', Validators.required],
2470
+ NOME_CAMPO_dateB: ['', Validators.required]
2471
+ }, { validator: AgroFormValidator.dateComparisonValidator('NOME_CAMPO_dateA', 'NOME_CAMPO_dateB') });
2472
+ * @param controlNameA
2473
+ * @param controlNameB
2474
+ * @returns
2475
+ */
2476
+ static compareDateWithOtherDateField(controlNameA, controlNameB) {
2477
+ const compareDate = (control) => {
2478
+ var _a, _b, _c, _d, _e;
2479
+ const formGroup = control;
2480
+ const dateA = (_a = formGroup.get(controlNameA)) === null || _a === void 0 ? void 0 : _a.value;
2481
+ const dateB = (_b = formGroup.get(controlNameB)) === null || _b === void 0 ? void 0 : _b.value;
2482
+ const methodName = 'compareDateWithOtherDateField';
2483
+ if (dateA && dateB) {
2484
+ const dateAObj = new Date(dateA);
2485
+ const dateBObj = new Date(dateB);
2486
+ if (dateAObj < dateBObj) {
2487
+ (_c = formGroup.get(controlNameA)) === null || _c === void 0 ? void 0 : _c.setErrors({ [methodName]: true });
2488
+ return { [methodName]: true };
2489
+ }
2490
+ else if ((_d = formGroup.get(controlNameA)) === null || _d === void 0 ? void 0 : _d.hasError(methodName)) {
2491
+ (_e = formGroup.get(controlNameA)) === null || _e === void 0 ? void 0 : _e.setErrors(null);
2492
+ }
2493
+ }
2494
+ return null;
2495
+ };
2496
+ return compareDate;
2497
+ }
2498
+ /**
2499
+ * Validator para checar se um campo de números é maior ou menor que outro campo.
2500
+ *
2501
+ * Aplique esse validator no FormGroup, passando os nomes dos campos que deseja comparar.
2502
+ * @example
2503
+ * this.myForm = this.fb.group({
2504
+ * NUMERO_A: ['', Validators.required],
2505
+ * NUMERO_B: ['', Validators.required]
2506
+ * }, { validator: AgroFormValidator.compareNumberFields('NUMERO_A', 'NUMERO_B', NumberComparisonType.EQUALS) });
2507
+ *
2508
+ * Neste caso, a verificação será se o NUMERO_A é igual ao NUMERB_B.
2509
+ * @param controlNameA
2510
+ * @param controlNameB
2511
+ * @returns
2512
+ */
2513
+ static compareNumberFields(controlNameA, controlNameB, comparisonMethod) {
2514
+ const compareNumber = (control) => {
2515
+ var _a, _b, _c;
2516
+ const formGroup = control;
2517
+ const numberA = (_a = formGroup.get(controlNameA)) === null || _a === void 0 ? void 0 : _a.value;
2518
+ const numberB = (_b = formGroup.get(controlNameB)) === null || _b === void 0 ? void 0 : _b.value;
2519
+ const methodName = 'compareNumberFields';
2520
+ if (numberA && numberB) {
2521
+ const errorType = NumberComparisonType[comparisonMethod];
2522
+ const errorCondition = {
2523
+ [NumberComparisonType.EQUALS]: numberA !== numberB,
2524
+ [NumberComparisonType.GREATER_THAN]: numberA <= numberB,
2525
+ [NumberComparisonType.LESS_THAN]: numberA >= numberB,
2526
+ [NumberComparisonType.GREATER_THAN_OR_EQUAL]: numberA < numberB,
2527
+ [NumberComparisonType.LESS_THAN_OR_EQUAL]: numberA > numberB,
2528
+ [NumberComparisonType.NOT_EQUALS]: numberA === numberB
2529
+ };
2530
+ if (errorCondition[comparisonMethod]) {
2531
+ const controlA = formGroup.get(controlNameA);
2532
+ if (controlA) {
2533
+ controlA.setErrors({ [methodName]: comparisonMethod });
2534
+ }
2535
+ return { [methodName]: errorType };
2536
+ }
2537
+ else if ((_c = formGroup.get(controlNameA)) === null || _c === void 0 ? void 0 : _c.hasError(methodName)) {
2538
+ const controlA = formGroup.get(controlNameA);
2539
+ if (controlA) {
2540
+ controlA.setErrors(null);
2541
+ }
2542
+ }
2543
+ }
2544
+ return null;
2545
+ };
2546
+ return compareNumber;
2547
+ }
2548
+ /**
2549
+ * Validator para checar se um valor está entre os demais valores de três formControls.
2550
+ *
2551
+ * Aplique esse validator no FormGroup, passando os nomes dos três formControls que deseja comparar.
2552
+ * @example
2553
+ * this.myForm = this.fb.group({
2554
+ * minorFormControl: ['', Validators.required],
2555
+ * targetFormControl: ['', Validators.required],
2556
+ * majorFormControl: ['', Validators.required]
2557
+ * }, { validator: AgroFormValidator.checkValueBetween('minorFormControl', 'targetFormControl', 'majorFormControl') });
2558
+ *
2559
+ * Neste caso, a verificação será se o targetFormControl está entre o minorFormControl e o majorFormControl.
2560
+ * @param minorFormControl
2561
+ * @param targetFormControl
2562
+ * @param majorFormControl
2563
+ * @returns
2564
+ */
2565
+ static checkValueBetween(minorFormControl, targetFormControl, majorFormControl) {
2566
+ const checkValue = (control) => {
2567
+ var _a, _b, _c, _d;
2568
+ const formGroup = control;
2569
+ const valueA = (_a = formGroup.get(minorFormControl)) === null || _a === void 0 ? void 0 : _a.value;
2570
+ const valueB = (_b = formGroup.get(targetFormControl)) === null || _b === void 0 ? void 0 : _b.value;
2571
+ const valueC = (_c = formGroup.get(majorFormControl)) === null || _c === void 0 ? void 0 : _c.value;
2572
+ const methodName = 'checkValueBetween';
2573
+ if (valueA && valueB && valueC) {
2574
+ if (valueB < valueA || valueB > valueC) {
2575
+ const targetControl = formGroup.get(targetFormControl);
2576
+ if (targetControl) {
2577
+ targetControl.setErrors({ [methodName]: true });
2578
+ }
2579
+ return { [methodName]: true };
2580
+ }
2581
+ else if ((_d = formGroup.get(targetFormControl)) === null || _d === void 0 ? void 0 : _d.hasError(methodName)) {
2582
+ const targetControl = formGroup.get(targetFormControl);
2583
+ if (targetControl) {
2584
+ targetControl.setErrors(null);
2585
+ }
2586
+ }
2587
+ }
2588
+ return null;
2589
+ };
2590
+ return checkValue;
2591
+ }
2592
+ /**
2593
+ * Validator para checar se o campo é um objeto e se possui uma propriedade específica.
2594
+ *
2595
+ * @example
2596
+ * this.myForm = this.fb.group({
2597
+ * OBJETO_FIELD: ['', [Validators.required, AgroFormValidator.objectPropertyValidator('propriedade')]]
2598
+ * });
2599
+ * @param propertyName
2600
+ * @returns
2601
+ */
2602
+ static objectPropertyValidator(propertyName) {
2603
+ const objectProperty = (control) => {
2604
+ const methodName = 'objectProperty';
2605
+ if (AgroObjectUtils.isObject(control.value) && AgroObjectUtils.containsProperty(control.value, propertyName)) {
2606
+ control.setErrors(null);
2607
+ return null;
2608
+ }
2609
+ control.setErrors({ [methodName]: true });
2610
+ return { [methodName]: true };
2611
+ };
2612
+ return objectProperty;
2613
+ }
2614
+ /**
2615
+ * Verifica se a string informada é um CPF válido.
2616
+ * Se a validação for false, retorna um objeto com a chave cpfValidator.
2617
+ */
2618
+ static CPFValidator(control) {
2619
+ const cpf = control.value;
2620
+ if (!cpf) {
2621
+ return null;
2622
+ }
2623
+ return AgroStringUtils.validateCPF(cpf) ? null : { cpfValidator: true };
2624
+ }
2625
+ /**
2626
+ * Verifica se a string informada é um CNPJ válido.
2627
+ * Se a validação for false, retorna um objeto com a chave cnpjValidator.
2628
+ */
2629
+ static CNPJValidator(control) {
2630
+ const cnpj = control.value;
2631
+ if (!cnpj) {
2632
+ return null;
2633
+ }
2634
+ return AgroStringUtils.validateCNPJ(cnpj) ? null : { cnpjValidator: true };
2635
+ }
2636
+ /**
2637
+ * Verifica se a string informada é uma placa de veículo válido.
2638
+ * Se a validação for false, retorna um objeto com a chave licensePlate.
2639
+ */
2640
+ static licensePlateValidator(control) {
2641
+ const plate = control.value;
2642
+ if (!plate) {
2643
+ return null;
2644
+ }
2645
+ return AgroStringUtils.isValidLicensePlate(plate) ? null : { licensePlate: true };
2646
+ }
2647
+ }
2648
+
2625
2649
  class AsyncLock {
2626
2650
  constructor() {
2627
2651
  this.queue = [];