-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInnerFormValidation.js
More file actions
3091 lines (2735 loc) · 123 KB
/
InnerFormValidation.js
File metadata and controls
3091 lines (2735 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function ($) {
/**
* InnerFormValidation Configuration and Functions
*/
$.innerForm = $.innerForm || {};
/**
* Enables or disables verbose logging for debugging purposes.
*/
$.innerForm.verbose = $.innerForm.verbose || false;
/**
* Timeout duration (in milliseconds) for input type events before triggering validation.
*/
$.innerForm.onTypeTimeout = 900;
$.innerForm.isDeleting = false;
/**
* Logs messages to the console when verbose mode is enabled.
* @function log
* @memberof $.innerForm
* @param {...*} arguments - Arguments to log to console
*/
$.innerForm.log = function () {
if ($.innerForm.verbose) console.log("InnerFormValidation:", arguments);
}
/**
* Logs error messages to the console when verbose mode is enabled.
* @function error
* @memberof $.innerForm
* @param {...*} arguments - Arguments to log as error
*/
$.innerForm.error = function () {
if ($.innerForm.verbose) console.error("InnerFormValidation:", arguments);
}
/**
* Logs warning messages to the console when verbose mode is enabled.
* @function warn
* @memberof $.innerForm
* @param {...*} arguments - Arguments to log as warning
*/
$.innerForm.warn = function () {
if ($.innerForm.verbose) console.warn("InnerFormValidation:", arguments);
}
/**
* Adds leading zeros to a number to reach the specified total length.
* @function addLeadingZeros
* @memberof $.innerForm
* @param {string|number} num - The number to pad with zeros
* @param {number} totalLength - The desired total length of the string
* @returns {string} The padded string
*/
$.innerForm.addLeadingZeros = function (num, totalLength) {
num = num || ""
num = jQuery.trim(`${num}`);
if (!isNaN(num) && num < 0) {
const withoutMinus = String(num).slice(1);
return '-' + withoutMinus.padStart(totalLength, '0');
}
return String(num).padStart(totalLength, '0');
}
/**
* Calculates the checksum for a barcode using standard algorithms.
* @function barcodeCheckSum
* @memberof $.innerForm
* @param {string} code - The barcode string to calculate checksum for
* @returns {number} The calculated checksum digit
*/
$.innerForm.barcodeCheckSum = function (code) {
code = code || ""
let i = 0;
let p = 0;
let t = code.length;
for (var j = 1; j <= t; j++) {
if ((j & ~-2) == 0) {
p += parseInt(code.slice(j - 1, j));
}
else {
i += parseInt(code.slice(j - 1, j));
}
}
if ((t == 7 || t == 11)) {
i = i * 3 + p;
p = parseInt((i + 9) / 10) * 10;
t = p - i;
} else {
p = p * 3 + i;
i = parseInt((p + 9) / 10) * 10;
t = i - p;
}
return t;
}
/**
* Validates time format (HH:MM or HH:MM:SS or MM:SS).
* @function validateTime
* @memberof $.innerForm
* @param {string} value - The time string to validate
* @param {boolean} [minutesSeconds=false] - If true, validates as MM:SS format
* @returns {boolean} True if the time format is valid, false otherwise
*/
$.innerForm.validateTime = function (value, minutesSeconds) {
minutesSeconds = minutesSeconds || false;
var comp = value.split(":");
if (comp.length == 3) {
minutesSeconds == false;
var h = parseInt(comp[0], 10);
var m = parseInt(comp[1], 10);
var s = parseInt(comp[2], 10);
let ff = h <= 23 && h >= 0 && m <= 59 && m >= 0 && s >= 0 && s <= 59;
return ff;
}
if (comp.length == 2) {
if (minutesSeconds) {
var m = parseInt(comp[0], 10);
var s = parseInt(comp[1], 10);
let ff = m <= 59 && m >= 0 && s >= 0 && s <= 59;
return ff;
} else {
var h = parseInt(comp[0], 10);
var m = parseInt(comp[1], 10);
let ff = h <= 23 && h >= 0 && m <= 59 && m >= 0;
return ff;
}
}
return false;
}
/**
* Validates EAN (European Article Number) barcode format and checksum.
* @function validateEAN
* @memberof $.innerForm
* @param {string} value - The EAN code to validate
* @returns {boolean} True if the EAN is valid, false otherwise
*/
$.innerForm.validateEAN = function (value) {
value = value || ""
if (!isNaN(value) && value.length > 1 && value.length <= 16) {
let bar = value.slice(0, -1);
let ver = value.slice(-1);
return $.innerForm.barcodeCheckSum(bar) == ver;
}
return false;
}
/**
* Calculates age based on birth date and reference date.
* @function getAge
* @memberof $.innerForm
* @param {string|Date} birthDate - The birth date
* @param {Date} [fromDate=new Date()] - Reference date to calculate age from
* @returns {number} The calculated age in years
*/
$.innerForm.getAge = function (birthDate, fromDate) {
fromDate = fromDate || new Date();
return Math.floor((fromDate - $.innerForm.parseDateInt(birthDate)) / 3.15576e+10);
};
/**
* Validates that a value does not contain any of the specified characters.
* @function validateNotChar
* @memberof $.innerForm
* @param {string} value - The input value to check
* @param {string} chars - String of characters that should not be present
* @returns {boolean} True if none of the characters are found, false otherwise
*/
$.innerForm.validateNotChar = function (value, chars) {
chars = chars.split("");
for (var i = 0; i < chars.length; i++) {
if (value.indexOf(chars[i]) >= 0) {
return false;
}
}
return true;
};
/**
* Validates if a value is a valid UUID (Universally Unique Identifier).
* Accepts both RFC 4122 compliant UUIDs and more flexible GUID formats.
* @function validateUUID
* @memberof $.innerForm
* @param {string} value - The UUID string to validate
* @returns {boolean} True if the value is a valid UUID, false otherwise
*/
$.innerForm.validateUUID = function (value) {
value = value || "";
// More flexible UUID pattern that accepts any hexadecimal characters
// Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
return value != "00000000-0000-0000-0000-000000000000" && uuidPattern.test(value);
};
/**
* Validates latitude coordinate values.
* @function validateLatitude
* @memberof $.innerForm
* @param {string} value - The latitude value to validate
* @returns {boolean} True if the value is a valid latitude (-90 to +90), false otherwise
*/
$.innerForm.validateLatitude = function (value) {
value = value || "";
// Remove espaços e substitui vírgula por ponto
value = value.trim().replace(',', '.');
// Verifica se é um número válido
var numValue = parseFloat(value);
// Valida se é um número e está dentro dos limites da latitude
return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
};
/**
* Validates longitude coordinate values.
* @function validateLongitude
* @memberof $.innerForm
* @param {string} value - The longitude value to validate
* @returns {boolean} True if the value is a valid longitude (-180 to +180), false otherwise
*/
$.innerForm.validateLongitude = function (value) {
value = value || "";
// Remove espaços e substitui vírgula por ponto
value = value.trim().replace(',', '.');
// Verifica se é um número válido
var numValue = parseFloat(value);
// Valida se é um número e está dentro dos limites da longitude
return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
};
/**
* Validates coordinate pairs in various formats.
* @function validateCoordinate
* @memberof $.innerForm
* @param {string} value - The coordinate value to validate (e.g., "lat,lng" or "lat lng")
* @returns {boolean} True if the value contains valid coordinates, false otherwise
*/
$.innerForm.validateCoordinate = function (value) {
value = value || "";
// Remove espaços extras e substitui vírgulas por pontos nos decimais
value = value.trim();
// Tenta diferentes formatos de separação
var coords = [];
if (value.includes(',')) {
coords = value.split(',');
} else if (value.includes(' ')) {
coords = value.split(/\s+/);
} else if (value.includes(';')) {
coords = value.split(';');
} else {
return false; // Formato não reconhecido
}
// Deve ter exatamente 2 coordenadas
if (coords.length !== 2) {
return false;
}
var lat = coords[0].trim().replace(',', '.');
var lng = coords[1].trim().replace(',', '.');
// Valida ambas as coordenadas
return $.innerForm.validateLatitude(lat) && $.innerForm.validateLongitude(lng);
};
/**
* Validates that a value contains at least one of the specified characters.
* @function validateAnyChar
* @memberof $.innerForm
* @param {string} value - The input value to check
* @param {string} chars - String of characters where at least one should be present
* @returns {boolean} True if any of the characters are found, false otherwise
*/
$.innerForm.validateAnyChar = function (value, chars) {
chars = chars.split("");
var v = [];
for (var i = 0; i < chars.length; i++) {
if (value.indexOf(chars[i]) >= 0) {
v.push(true);
}
}
return v.indexOf(true) >= 0;
};
/**
* Validates that a value contains all of the specified characters.
* @function validateAllChar
* @memberof $.innerForm
* @param {string} value - The input value to check
* @param {string} chars - String of characters that must all be present
* @returns {boolean} True if all characters are found, false otherwise
*/
$.innerForm.validateAllChar = function (value, chars) {
chars = chars.split("");
var v = [];
for (var i = 0; i < chars.length; i++) {
if (value.indexOf(chars[i]) >= 0) {
v.push(true);
} else { v.push(false); }
}
return v.indexOf(false) < 0;
};
/**
* Validates if a date string represents a valid date.
* @function validDate
* @memberof $.innerForm
* @param {string} value - The date string to validate (DD/MM/YYYY format)
* @returns {boolean} True if the date is valid, false otherwise
*/
$.innerForm.validDate = function (value) {
var datenumber = $.innerForm.parseDateInt(value);
return datenumber != null && !isNaN(datenumber);
}
/**
* Parses a date string and returns a int object.
* @function parseDate
* @memberof $.innerForm
* @param {string} value - The date string to parse (DD/MM/YYYY or MM/YYYY format)
* @returns {Date|null} The parsed Date object or null if invalid
*/
$.innerForm.parseDateInt = function (value) {
var dt = 0;
var d = 0;
var m = 0;
var y = 0;
var comp = value.split(" ")[0].split("/") ?? value.split("/");
if (comp.length == 3) {
comp[2] = comp[2].length == 2 ? $.innerForm.expandYear(comp[2]) : comp[2];
d = parseInt(comp[0], 10);
m = parseInt(comp[1], 10) - 1;
y = parseInt(comp[2], 10);
}
if (comp.length == 2) {
comp[1] = comp[1].length == 2 ? $.innerForm.expandYear(comp[1]) : comp[1];
d = 1
m = parseInt(comp[0], 10) - 1;
y = parseInt(comp[1], 10);
}
dt = new Date(y, m, d);
var lastday = new Date(y, m + 1, 0);
if (m > 11 || m < 0) { return null }
if (d > lastday.getDate() || d < 1) { return null }
if (dt > 0) { return dt * 1 };
return null;
}
/**
* Parses a date string and returns a Date object.
* @function parseDate
* @memberof $.innerForm
* @param {string} value - The date string to parse (DD/MM/YYYY or MM/YYYY format)
* @returns {Date|null} The parsed Date object or null if invalid
*/
$.innerForm.parseDate = function (value) {
value = value || "";
var datenumber = $.innerForm.parseDateInt(value);
if (datenumber != null) {
return new Date(datenumber);
}
return null;
}
/**
* Validates a date range string in format "DD/MM/YYYY ~ DD/MM/YYYY"
* @param {string} value - Date range string
* @returns {boolean} True if both dates are valid and first date <= second date
*/
$.innerForm.validDateRange = function (value) {
if (!value || typeof value !== 'string') return false;
var parts = value.split(' ~ ');
if (parts.length !== 2) return false;
var date1 = parts[0].trim();
var date2 = parts[1].trim();
// Validate both dates individually
if (!$.innerForm.validDate(date1) || !$.innerForm.validDate(date2)) {
return false;
}
// Parse both dates to compare
var parsedDate1 = $.innerForm.parseDateInt(date1);
var parsedDate2 = $.innerForm.parseDateInt(date2);
// First date should be <= second date
return parsedDate1 <= parsedDate2;
}
/**
* Validates a month/year range string in format "MM/YYYY ~ MM/YYYY"
* @param {string} value - Month/year range string
* @returns {boolean} True if both month/years are valid and first <= second
*/
$.innerForm.validMonthYearRange = function (value) {
if (!value || typeof value !== 'string') return false;
var parts = value.split(' ~ ');
if (parts.length !== 2) return false;
var monthYear1 = parts[0].trim();
var monthYear2 = parts[1].trim();
// Validate both month/years individually (add day 01 for validation)
var testDate1 = "01/" + monthYear1;
var testDate2 = "01/" + monthYear2;
return $.innerForm.validDateRange(testDate1 + " ~ " + testDate2);
}
/**
* Validates a short month/year range string in format "MM/YY ~ MM/YY"
* @function validShortMonthYearRange
* @memberof $.innerForm
* @param {string} value - Short month/year range string
* @returns {boolean} True if both month/years are valid and first <= second
*/
$.innerForm.validShortMonthYearRange = function (value) {
if (!value || typeof value !== 'string') return false;
var parts = value.split(' ~ ');
if (parts.length !== 2) return false;
var shortMonthYear1 = parts[0].trim();
var shortMonthYear2 = parts[1].trim();
// Convert short year format to full year and validate
var comp1 = shortMonthYear1.split('/');
var comp2 = shortMonthYear2.split('/');
if (comp1.length !== 2 || comp2.length !== 2) return false;
// Expand short years to full years
var fullYear1 = $.innerForm.expandYear(parseInt(comp1[1], 10), 20, 5);
var fullYear2 = $.innerForm.expandYear(parseInt(comp2[1], 10), 20, 5);
var fullMonthYear1 = comp1[0] + "/" + fullYear1;
var fullMonthYear2 = comp2[0] + "/" + fullYear2;
return $.innerForm.validMonthYearRange(fullMonthYear1 + " ~ " + fullMonthYear2);
}
/**
* Expands a short year (YY) to a full year (YYYY) based on the current century.
* If the expanded year is outside the range of (currentYear - pastDistance) to (currentYear + futureDistance),
* it is adjusted to the previous century.
* @function expandYear
* @memberof $.innerForm
* @param {number} year - The short year to expand.
* @param {number} pastDistance - The number of years to consider for the past.
* @param {number} futureDistance - The number of years to consider for the future.
* @returns {number} The expanded full year
*/
$.innerForm.expandYear = function (year, pastDistance, futureDistance) {
const currentYear = new Date().getFullYear();
const century = Math.floor(currentYear / 100) * 100;
pastDistance = pastDistance || (currentYear - century);
futureDistance = futureDistance || 5;
if ($.innerForm.isNumber(pastDistance)) {
pastDistance = parseInt(pastDistance, 10);
} else {
pastDistance = currentYear - century;
}
if ($.innerForm.isNumber(futureDistance)) {
futureDistance = parseInt(futureDistance, 10);
} else {
futureDistance = 5;
}
if ($.innerForm.isNumber(year)) {
year = parseInt(year, 10);
} else {
$.innerForm.warn("Invalid year:", year);
year = new Date().getFullYear();
}
if (year < 0) year = -year;
if (year >= 1000) {
return year;
}
if (year > 99 && year <= 999) {
year = century + year;
year -= 1000;
return year;
} else {
year = century + year;
}
let limitBefore = (currentYear - pastDistance);
let limitAfter = (currentYear + futureDistance);
/// se o ano digitado estiver fora do range, então é do século anterior
if (year < limitBefore || year > limitAfter) {
year -= 100;
}
return year;
}
/**
* Applies a UUID mask to an input field, formatting it as a standard UUID.
* @function applyUUIDMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyUUIDMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
text = text.replace(/[^a-zA-Z0-9]/g, '');
/// add dashes during type
text = text.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5');
if (text.length > 36) {
text = text.substring(0, 36);
input.maxLength = 36;
}
input.value = text;
}
/**
* Applies a latitude mask to format and validate latitude coordinates.
* @function applyLatitudeMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyLatitudeMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
// Remove caracteres inválidos, mantendo apenas números, ponto, vírgula e sinal de menos
text = text.replace(/[^0-9.,-]/g, '');
// Substitui vírgula por ponto
text = text.replace(',', '.');
// Garante apenas um sinal de menos no início
if (text.indexOf('-') > 0) {
text = text.replace(/-/g, '');
}
if (text.split('-').length > 2) {
text = text.substring(0, text.lastIndexOf('-'));
}
// Garante apenas um ponto decimal
var dotIndex = text.indexOf('.');
if (dotIndex !== -1) {
text = text.substring(0, dotIndex + 1) + text.substring(dotIndex + 1).replace(/\./g, '');
}
// Limita casas decimais baseado na classe 'precision'
var classes = (input.className || '').split(' ');
var precisionIndex = classes.indexOf('precision');
var precision = 6; // padrão
if (precisionIndex !== -1 && classes[precisionIndex + 1]) {
precision = parseInt(classes[precisionIndex + 1]) || 6;
}
if (dotIndex !== -1 && text.length > dotIndex + precision + 1) {
text = text.substring(0, dotIndex + precision + 1);
}
// Valida limites de latitude (-90 a +90)
var numValue = parseFloat(text);
if (!isNaN(numValue)) {
if (numValue > 90) {
text = "90";
} else if (numValue < -90) {
text = "-90";
}
}
input.value = text;
};
/**
* Applies a longitude mask to format and validate longitude coordinates.
* @function applyLongitudeMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyLongitudeMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
// Remove caracteres inválidos, mantendo apenas números, ponto, vírgula e sinal de menos
text = text.replace(/[^0-9.,-]/g, '');
// Substitui vírgula por ponto
text = text.replace(',', '.');
// Garante apenas um sinal de menos no início
if (text.indexOf('-') > 0) {
text = text.replace(/-/g, '');
}
if (text.split('-').length > 2) {
text = text.substring(0, text.lastIndexOf('-'));
}
// Garante apenas um ponto decimal
var dotIndex = text.indexOf('.');
if (dotIndex !== -1) {
text = text.substring(0, dotIndex + 1) + text.substring(dotIndex + 1).replace(/\./g, '');
}
// Limita casas decimais baseado na classe 'precision'
var classes = (input.className || '').split(' ');
var precisionIndex = classes.indexOf('precision');
var precision = 6; // padrão
if (precisionIndex !== -1 && classes[precisionIndex + 1]) {
precision = parseInt(classes[precisionIndex + 1]) || 6;
}
if (dotIndex !== -1 && text.length > dotIndex + precision + 1) {
text = text.substring(0, dotIndex + precision + 1);
}
// Valida limites de longitude (-180 a +180)
var numValue = parseFloat(text);
if (!isNaN(numValue)) {
if (numValue > 180) {
text = "180";
} else if (numValue < -180) {
text = "-180";
}
}
input.value = text;
};
/**
* Applies a mask that removes all spaces from the input.
* @function applyNoSpaceMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyNoSpaceMask = function (input = new HTMLInputElement()) {
input.value = input.value
.replace(/[ ]+/g, '');
};
/**
* Applies an alphabetic mask that allows only letters and spaces.
* @function applyAlphaMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyAlphaMask = function (input = new HTMLInputElement()) {
input.value = input.value
.replace(/[!@#$%¨&*()_+\d\-=¹²³£¢¬§´[`{\/?°ª~\]^}º\\,.;|<>:₢«»"'¶¿®þ]/g, '')
.replace(/[ ]+/g, ' ');
};
/**
* Applies an alphanumeric mask that allows letters, numbers, and spaces.
* @function applyAlphaNumericMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyAlphaNumericMask = function (input = new HTMLInputElement()) {
input.value = input.value
.replace(/[!@#$%¨&*()_+\-=¹²³£¢¬§´[`{\/?°ª~\]^}º\\,.;|<>:₢«»"'¶¿®þ]/g, '')
.replace(/[ ]+/g, ' ');
};
/**
* Applies a phone number mask (Brazilian format).
* @function applyPhoneMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyPhoneMask = function (input = new HTMLInputElement()) {
var value = input.value;
value = value.replace(/\D/g, "");
value = value.replace(/^(\d{4})(\d{1,4})$/g, "$1-$2");
value = value.replace(/^(\d{5})(\d{1,4})$/g, "$1-$2");
value = value.replace(/^(\d{2})(\d{4})(\d{1,4})$/g, "($1) $2-$3");
value = value.replace(/^(\d{2})(\d{5})(\d{1,4})$/g, "($1) $2-$3");
input.maxLength = 15;
input.value = value;
};
$.innerForm.applyUpperMask = function (input = new HTMLInputElement()) {
input.value = input.value.toUpperCase();
};
$.innerForm.applyLowerMask = function (input = new HTMLInputElement()) {
input.value = input.value.toLowerCase();
};
$.innerForm.applyDateMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
if ($.innerForm.isDeleting == false) {
text = $.innerForm.formatDate(text);
}
if (/^[\d]{2}\/[\d]{2}\/[\d]{4}$/g.test(text)) {
input.maxLength = text.length;
}
input.value = text;
};
/**
* Formats a date string by adding separators (DD/MM/YYYY format).
* @function formatDate
* @memberof $.innerForm
* @param {string} text - The date string to format
* @returns {string} The formatted date string
*/
$.innerForm.formatDate = function (text) {
text = text || "";
text = $.innerForm.parseDatePartial(text);
// remove tudo que nao for numero ou barra
text = text.replace(/[^\d\/]/g, "");
if (text.length > 10) text = text.substring(0, 10);
return text;
}
/**
* Applies a date-time mask (DD/MM/YYYY HH:MM:SS format).
* @function applyDateTimeMask
* @memberof $.innerForm
* @param {HTMLInputElement} [input] - The input element to apply the mask to
*/
$.innerForm.applyDateTimeMask = function (input = new HTMLInputElement()) {
var value = input.value.replace(/\D/g, "");
value = value.replace(/^(\d{2})(\d+)$/g, "$1/$2");
value = value.replace(/^(\d{2}\/\d{2})(\d+)$/g, "$1/$2");
value = value.replace(/^(\d{2}\/\d{2}\/\d{4})(\d+)$/g, "$1 $2");
value = value.replace(/^(\d{2}\/\d{2}\/\d{4} \d{2})(\d+)$/g, "$1:$2");
value = value.replace(/^(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2})(\d+)$/g, "$1:$2");
input.value = value;
input.maxLength = 19;
};
$.innerForm.applyDateShortMask = function (input = new HTMLInputElement()) {
var value = input.value.replace(/\D/g, "");
value = value.replace(/^(\d{2})(\d+)$/g, "$1/$2");
value = value.replace(/^(\d{2}\/\d{2})(\d+)$/g, "$1/$2");
value = value.replace(/^(\d{2}\/\d{2}\/\d{4})(\d+)$/g, "$1 $2");
value = value.replace(/^(\d{2}\/\d{2}\/\d{4} \d{2})(\d+)$/g, "$1:$2");
input.value = value;
input.maxLength = 16;
};
$.innerForm.applyTimeMask = function (input = new HTMLInputElement()) {
var value = input.value.replace(/\D/g, "");
value = value.replace(/^(\d{2})(\d+)$/g, "$1:$2");
input.value = value.replace(/^(\d{2}:\d{2})(\d{1,2})$/g, "$1:$2");
input.maxLength = 8;
};
$.innerForm.applyShortTimeMask = function (input = new HTMLInputElement()) {
var value = input.value.replace(/\D/g, "");
input.value = value.replace(/^(\d{2})(\d{1,2})$/g, "$1:$2");
input.maxLength = 5;
};
$.innerForm.applyCPForCNPJMask = function (input = new HTMLInputElement()) {
var value = input.value;
value = value.replace(/\D/g, "");
if (value.length <= 11) {
value = value.replace(/^(\d{3})(\d+)$/g, "$1.$2");
value = value.replace(/^(\d{3}\.\d{3})(\d+)$/g, "$1.$2");
value = value.replace(/^(\d{3}\.\d{3}\.\d{3})(\d{1,2})$/g, "$1-$2");
} else {
value = value.replace(/^(\d{2})(\d+)$/g, "$1.$2");
value = value.replace(/^(\d{2}\.\d{3})(\d+)$/g, "$1.$2");
value = value.replace(/^(\d{2}\.\d{3}\.\d{3})(\d+)$/g, "$1/$2");
value = value.replace(/^(\d{2}\.\d{3}\.\d{3}\/\d{4})(\d{1,2})$/g, "$1-$2");
}
input.value = value;
input.maxLength = 18;
};
$.innerForm.applyCPFMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
text = text.replace(/\D/g, "");
text = text.replace(/^(\d{3})(\d+)/g, "$1.$2");
text = text.replace(/^(\d{3}\.\d{3})(\d+)/g, "$1.$2");
text = text.replace(/^(\d{3}\.\d{3}\.\d{3})(\d{1,2})$/g, "$1-$2");
if (/^[\d]{3}\.[\d]{3}\.[\d]{3}-[\d]{2}$/g.test(text)) {
input.maxLength = text.length;
}
input.value = text;
};
$.innerForm.applyCEPMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
text = text.replace(/\D/g, "");
// Limita a 8 dígitos
if (text.length > 8) {
text = text.substring(0, 8);
}
// Só aplica a formatação se tiver 6 ou mais dígitos
if (text.length >= 6) {
text = text.replace(/^(\d{5})(\d{1,3})$/g, "$1-$2");
}
// Define maxLength baseado no formato final esperado
input.maxLength = 9; // "00000-000"
input.value = text;
};
/**
* Applies a CNPJ mask to format the input as a CNPJ number.
* @function applyCNPJMask
* @memberof $.innerForm
* @param {*} input
*/
$.innerForm.applyCNPJMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
text = text.replace(/\D/g, "");
text = text.replace(/^(\d{2})(\d+)/, "$1.$2");
text = text.replace(/^(\d{2}\.\d{3})(\d+)/g, "$1.$2");
text = text.replace(/^(\d{2}\.\d{3}\.\d{3})(\d+)/g, "$1/$2");
text = text.replace(/^(\d{2}\.\d{3}\.\d{3}\/\d{4})(\d{1,2})$/g, "$1-$2");
if (/^[\d]{2}\.[\d]{3}\.[\d]{3}\/[\d]{4}-[\d]{2}$/g.test(text)) {
input.maxLength = text.length;
}
input.value = text;
};
$.innerForm.applyCreditCardMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
text = text.replace(/\D/g, "");
text = text.replace(/^(\d{4})(\d+)$/g, "$1 $2");
text = text.replace(/^(\d{4} \d{4})(\d+)$/g, "$1 $2");
text = text.replace(/^(\d{4} \d{4} \d{4})(\d{1,4})$/g, "$1 $2");
if (/^[\d]{4} [\d]{4} [\d]{4} [\d]{4}$/g.test(text)) {
input.maxLength = text.length;
}
input.value = text;
};
$.innerForm.isNumber = function (n) {
if (n === null || n === undefined) return false;
if (typeof n === "string") n = n.trim();
try {
n = parseFloat(n);
return !isNaN(n) && isFinite(n);
} catch (error) {
return false;
}
}
/**
* Aplica máscara numérica considerando separador de milhares, decimal e casas decimais.
* @param {HTMLInputElement} input
*/
$.innerForm.applyNumberMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
var sep = input.getAttribute("data-separator");
var dec = input.getAttribute("data-decimal");
var thousand = input.getAttribute("data-thousand");
var hasSep = typeof sep === "string" && sep.length > 0;
var hasDec = typeof dec === "string" && dec.length > 0 && !isNaN(dec);
var hasThousand = typeof thousand === "string" && thousand.length > 0;
if (!hasSep && !hasDec) {
// Inteiro
text = text.replace(/\D/g, "");
if (hasThousand && thousand !== sep) {
// Adiciona separador de milhar
text = text.replace(/\B(?=(\d{3})+(?!\d))/g, thousand);
}
input.value = text;
return;
}
// Definir separador e casas decimais
if (!hasSep && hasDec) sep = ",";
if (hasSep && !hasDec) dec = "2";
if (hasSep && hasDec) { /* ok */ }
var sepRegex = sep.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
var thousandRegex = hasThousand ? thousand.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') : null;
// Remove tudo exceto dígitos, separador decimal e de milhar
var re = hasThousand ? new RegExp("[^\\d" + sepRegex + thousandRegex + "]", "g") : new RegExp("[^\\d" + sepRegex + "]", "g");
text = text.replace(re, "");
// Permitir só um separador decimal
var first = text.indexOf(sep);
if (first !== -1) {
var before = text.substring(0, first + 1);
var after = text.substring(first + 1).replaceAll(sep, "");
text = before + after;
}
// Limitar casas decimais
if (first !== -1 && dec > 0) {
var decs = text.substring(first + 1);
if (decs.length > dec) {
decs = decs.substring(0, dec);
text = text.substring(0, first + 1) + decs;
}
}
// Adicionar separador de milhar
if (hasThousand && thousand !== sep) {
var intPart = first !== -1 ? text.substring(0, first) : text;
var decPart = first !== -1 ? text.substring(first) : "";
intPart = intPart.replace(new RegExp(thousandRegex, 'g'), '');
intPart = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousand);
text = intPart + decPart;
}
input.value = text;
};
$.innerForm.applyMonthYearMask = function (input = new HTMLInputElement()) {
var text = input.value || "";
if ($.innerForm.isDeleting == false) {
text = $.innerForm.parseMonthYearPartial(text);
}
if (/^[\d]{2}\/[\d]{2}\/[\d]{4}$/g.test(text)) {
input.maxLength = text.length;
}
input.value = text;
};
/**
* Apply a date range mask to an input field.
* The expected format is "DD/MM/YYYY ~ DD/MM/YYYY".
* @param {HTMLInputElement} input
*/
$.innerForm.applyDateRangeMask = function (input = new HTMLInputElement()) {
if ($.innerForm.isDeleting == true) {
return;
}
// formato DD/MM/AAAA ~ DD/MM/AAAA
var text = input.value || "";
// Manter apenas dígitos, barras, ~ e espaços
text = text.replace(/[^\d\/~\s]/g, "");
text = text.replace(/\s+/g, " "); // Normalizar espaços
// Remover múltiplos tildes
text = text.replace(/~+/g, "~");
text = $.innerForm.parseDatePartial(text);
if (text.length > 23) text = text.substring(0, 23);
// se tiver o tilde, processa a segunda data
if (text.includes("~")) {
var parts = text.split("~");
var part1 = parts[0] ? parts[0].trim() : "";
var part2 = parts[1] ? parts[1].trim() : "";
var date1 = $.innerForm.parseDate(part1);
var date2 = $.innerForm.parseDate(part2);
if (date1 && date2) {
if (date1 > date2) {
part1 = `${date2.getDate().toString().padStart(2, '0')}/${(date2.getMonth() + 1).toString().padStart(2, '0')}/${date2.getFullYear()}`;
part2 = `${date1.getDate().toString().padStart(2, '0')}/${(date1.getMonth() + 1).toString().padStart(2, '0')}/${date1.getFullYear()}`;
}
}
text = part1 + " ~ " + part2;
}
input.value = text;
}
/**
* Parses and formats a partial short month/year string "MM/YY" during input.