-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInnerFormValidation.js
More file actions
4149 lines (3690 loc) · 170 KB
/
Copy pathInnerFormValidation.js
File metadata and controls
4149 lines (3690 loc) · 170 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 (root) {
var inputSelector = "input, select, textarea, button";
var toArray = function (value) { return Array.prototype.slice.call(value || []); };
var normalizeSelector = function (selector) {
return selector.replace(/:input/g, inputSelector);
};
var select = function (selector, context) {
context = context || (typeof document !== "undefined" ? document : null);
if ((typeof document !== "undefined" && selector === document) || (typeof window !== "undefined" && selector === window)) return [selector];
if (selector && selector.nodeType) return [selector];
if (selector && selector.elements) return selector.elements;
if (selector && selector.jquery) return toArray(selector);
if (typeof selector !== "string") return [];
if (!context || !context.querySelectorAll) return [];
if (selector.indexOf(":input") >= 0) {
return selector.split(",").reduce(function (result, part) {
var cleanPart = part.trim().replace(/:input/g, "") || "*";
return result.concat(toArray(context.querySelectorAll(cleanPart)).filter(function (element) {
return /^(INPUT|SELECT|TEXTAREA|BUTTON)$/.test(element.tagName);
}));
}, []);
}
return toArray(context.querySelectorAll(normalizeSelector(selector)));
};
var matches = function (element, selector) {
if (selector === ":checked") return !!element.checked;
if (selector === ":input") return /^(INPUT|SELECT|TEXTAREA|BUTTON)$/.test(element.tagName);
if (selector.indexOf(":input") >= 0) return matches(element, selector.replace(/:input/g, "")) && /^(INPUT|SELECT|TEXTAREA|BUTTON)$/.test(element.tagName);
return element.matches(selector);
};
var query = function (selector, context) {
var elements = Array.isArray(selector) ? selector : select(selector, context);
var api = Object.create(InnerForm.fn);
api.elements = elements;
api.length = elements.length;
for (var i = 0; i < elements.length; i++) api[i] = elements[i];
// O modo rascunho e' usado durante a inicializacao de formularios.
// Expor esses tres metodos tambem como propriedades da colecao evita
// que uma cadeia de prototipos alterada por integracoes externas deixe
// `InnerForm(form).undraft()` indisponivel.
["draft", "undraft", "isDraft"].forEach(function (method) {
if (typeof InnerForm.fn[method] === "function") {
api[method] = InnerForm.fn[method];
}
});
return api;
};
// ============================================
// Vanilla JS DOM Helpers (operate on element arrays)
// ============================================
var forEachElement = function (elements, callback) {
if (!elements || !elements.length) return;
for (var i = 0; i < elements.length; i++) {
callback.call(elements[i], elements[i], i);
}
};
var getElements = function (collection) {
return (collection && Array.isArray(collection.elements)) ? collection.elements : [];
};
var getFirstElement = function (elements) {
return elements && elements.length ? elements[0] : null;
};
var filterElements = function (elements, selector) {
if (!elements || !elements.length) return [];
return elements.filter(function (el) { return !matches(el, selector); });
};
var findElements = function (elements, selector) {
if (!elements || !elements.length) return [];
var found = [];
for (var i = 0; i < elements.length; i++) {
found = found.concat(select(selector, elements[i]));
}
return found;
};
var closestElement = function (elements, selector) {
if (!elements || !elements.length) return [];
var found = [];
for (var i = 0; i < elements.length; i++) {
var el = elements[i].closest(selector);
if (el) found.push(el);
}
return found;
};
var addClassToElements = function (elements, name) {
var classes = name.split(/\s+/);
forEachElement(elements, function (el) {
el.classList.add.apply(el.classList, classes);
});
};
var removeClassFromElements = function (elements, name) {
var classes = name.split(/\s+/);
forEachElement(elements, function (el) {
el.classList.remove.apply(el.classList, classes);
});
};
var hasClassOnElements = function (elements, name) {
if (!elements || !elements.length) return false;
for (var i = 0; i < elements.length; i++) {
if (elements[i].classList.contains(name)) return true;
}
return false;
};
var getAttrFromElements = function (elements, name) {
var el = getFirstElement(elements);
return el ? el.getAttribute(name) : undefined;
};
var setAttrOnElements = function (elements, name, value) {
forEachElement(elements, function (el) { el.setAttribute(name, value); });
};
var removeAttrFromElements = function (elements, name) {
forEachElement(elements, function (el) { el.removeAttribute(name); });
};
var getPropFromElements = function (elements, name) {
var el = getFirstElement(elements);
return el ? el[name] : undefined;
};
var setPropOnElements = function (elements, name, value) {
forEachElement(elements, function (el) { el[name] = value; });
};
var getDataFromElements = function (elements, name) {
name = name.replace(/^data-/, "");
var el = getFirstElement(elements);
return el ? el.dataset[name] : undefined;
};
var setDataOnElements = function (elements, name, value) {
name = name.replace(/^data-/, "");
forEachElement(elements, function (el) { el.dataset[name] = value; });
};
var getValFromElements = function (elements) {
var el = getFirstElement(elements);
return el && el.value !== undefined ? el.value : undefined;
};
var setValOnElements = function (elements, value) {
forEachElement(elements, function (el) { el.value = value; });
};
var getTextFromElements = function (elements) {
if (!elements || !elements.length) return "";
var texts = [];
for (var i = 0; i < elements.length; i++) {
texts.push(elements[i].textContent);
}
return texts.join("");
};
var setTextOnElements = function (elements, value) {
forEachElement(elements, function (el) { el.textContent = value; });
};
var appendHtmlToElements = function (elements, html) {
forEachElement(elements, function (el) { el.insertAdjacentHTML("beforeend", html); });
};
var triggerChangeOnElements = function (elements) {
forEachElement(elements, function (el) { el.dispatchEvent(new Event("change", { bubbles: true })); });
};
var triggerFocusOnElements = function (elements) {
forEachElement(elements, function (el) { if (el.focus) el.focus(); });
};
var onElements = function (elements, event, selector, handler) {
if (typeof selector === "function") { handler = selector; selector = null; }
forEachElement(elements, function (el) {
el.addEventListener(event, function (e) {
if (!selector || matches(e.target, selector)) handler.call(e.target, e);
});
});
};
var isElements = function (elements, selector) {
if (!elements || !elements.length) return false;
for (var i = 0; i < elements.length; i++) {
if (matches(elements[i], selector)) return true;
}
return false;
};
// Detecta se o modo rascunho esta' ativo para uma colecao de elementos.
// Considera a flag global InnerForm.draftMode, o atributo data-draft
// (qualquer valor exceto "false") e a classe .draft.
var isDraftMode = function (elements) {
if (InnerForm.draftMode) return true;
if (hasClassOnElements(elements, "draft")) return true;
var draftAttr = getAttrFromElements(elements, "data-draft");
return draftAttr !== undefined && draftAttr !== null && draftAttr !== "false";
};
/**
* InnerForm is a lightweight DOM manipulation and validation library.
* It provides methods for selecting elements, manipulating classes and attributes,
* and handling form validation.
*/
InnerForm = function (selector, context) { return query(selector, context); }
InnerForm.fn = {}
/**
* Normalizes any value into a string for validation purposes.
* Accepts inputs, strings, numbers, dates, jQuery objects and other objects.
* @function normalizeValue
* @memberof InnerFormValidation
* @param {*} value - Value to normalize (input element, string, number, Date, etc.)
* @returns {string} Normalized string value
*/
InnerForm.normalizeValue = function (value) {
// Se for um elemento de input, pega o valor
if (value instanceof HTMLInputElement || value instanceof HTMLTextAreaElement || value instanceof HTMLSelectElement) {
return String(value.value == null ? "" : value.value);
}
// Se for um objeto jQuery ou wrapper com .value
if (value && typeof value === "object" && "value" in value) {
return InnerForm.normalizeValue(value.value);
}
// Se for uma data, formata como DD/MM/YYYY
if (value instanceof Date && !isNaN(value.getTime())) {
var d = value.getDate().toString().padStart(2, "0");
var m = (value.getMonth() + 1).toString().padStart(2, "0");
return d + "/" + m + "/" + value.getFullYear();
}
// null, undefined ou vazio
if (value === null || value === undefined) return "";
// Converte para string
return String(value);
};
// API de colecao standalone. Essas operacoes existiam na API publica e
// usam os helpers nativos definidos acima; o adaptador jQuery continua
// apenas como camada opcional de compatibilidade.
InnerForm.fn.find = function (selector) {
return query(findElements(getElements(this), selector));
};
InnerForm.fn.each = function (callback) {
forEachElement(getElements(this), function (el, index) {
callback.call(el, index, el);
});
return this;
};
InnerForm.fn.first = function () { return query(getFirstElement(getElements(this))); };
InnerForm.fn.get = function (index) { return getElements(this)[index]; };
InnerForm.fn.addClass = function (name) { addClassToElements(getElements(this), name); return this; };
InnerForm.fn.removeClass = function (name) { removeClassFromElements(getElements(this), name); return this; };
InnerForm.fn.hasClass = function (name) { return hasClassOnElements(getElements(this), name); };
InnerForm.fn.attr = function (name, value) {
if (arguments.length === 1) return getAttrFromElements(getElements(this), name);
setAttrOnElements(getElements(this), name, value);
return this;
};
InnerForm.fn.removeAttr = function (name) { removeAttrFromElements(getElements(this), name); return this; };
InnerForm.fn.prop = function (name, value) {
if (arguments.length === 1) return getPropFromElements(getElements(this), name);
setPropOnElements(getElements(this), name, value);
return this;
};
InnerForm.fn.data = function (name, value) {
if (arguments.length === 1) return getDataFromElements(getElements(this), name);
setDataOnElements(getElements(this), name, value);
return this;
};
InnerForm.fn.val = function (value) {
if (arguments.length === 0) return getValFromElements(getElements(this));
setValOnElements(getElements(this), value);
return this;
};
InnerForm.fn.text = function (value) {
if (arguments.length === 0) return getTextFromElements(getElements(this));
setTextOnElements(getElements(this), value);
return this;
};
InnerForm.fn.append = function (html) { appendHtmlToElements(getElements(this), html); return this; };
InnerForm.fn.on = function (event, selector, handler) { onElements(getElements(this), event, selector, handler); return this; };
InnerForm.fn.change = function (handler) {
if (typeof handler === "function") onElements(getElements(this), "change", handler);
else triggerChangeOnElements(getElements(this));
return this;
};
InnerForm.fn.focus = function (handler) {
if (typeof handler === "function") onElements(getElements(this), "focus", handler);
else triggerFocusOnElements(getElements(this));
return this;
};
InnerForm.fn.not = function (selector) { return query(filterElements(getElements(this), selector)); };
InnerForm.fn.is = function (selector) { return isElements(getElements(this), selector); };
InnerForm.fn.closest = function (selector) { return query(closestElement(getElements(this), selector)); };
/**
* Removes leading and trailing whitespace from a value or input.
* @param {*} value - Value to trim
* @returns {string} Trimmed value
*/
InnerForm.trim = function (value) {
//se for um input, da trim no input e retorna, senao trata como texto
if (value instanceof HTMLInputElement || value instanceof HTMLTextAreaElement) {
value.value = InnerForm.trim(value.value);
return value;
}
//forca a conversão para string e trim
return InnerForm.normalizeValue(value).trim();
};
root.InnerForm = InnerForm;
/**
* Enables or disables verbose logging for debugging purposes.
*/
InnerForm.verbose = false;
/**
* Timeout duration (in milliseconds) for input type events before triggering validation.
*/
InnerForm.onTypeTimeout = 900;
/**
* Enables or disables draft mode globally. When active, the required rule
* (obg/req/required) is ignored so an incomplete form can be saved as a
* draft; all other validations still apply.
*/
InnerForm.draftMode = false;
var isDeleting = false;
/**
* Logs messages to the console when verbose mode is enabled.
* @function log
* @memberof InnerFormValidation
* @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 InnerFormValidation
* @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 InnerFormValidation
* @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 InnerFormValidation
* @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 = InnerForm.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 InnerFormValidation
* @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 InnerFormValidation
* @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) {
value = InnerForm.normalizeValue(value);
minutesSeconds = minutesSeconds || false;
if (!/^\d{1,2}:\d{2}(?::\d{2})?$/.test(value)) return 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 InnerFormValidation
* @param {string} value - The EAN code to validate
* @returns {boolean} True if the EAN is valid, false otherwise
*/
InnerForm.validateEAN = function (value) {
value = InnerForm.normalizeValue(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 InnerFormValidation
* @param {string|Date} birthDate - The birth date
* @param {Date} [atDate=new Date()] - Reference date to calculate age at
* @returns {number} The calculated age in years
*/
InnerForm.getAge = function (birthDate, atDate) {
atDate = atDate || new Date();
return Math.floor((atDate - InnerForm.parseDateInt(birthDate)) / 3.15576e+10);
};
/**
* Validates that a value does not contain any of the specified characters.
* @function validateNotChar
* @memberof InnerFormValidation
* @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) {
value = InnerForm.normalizeValue(value);
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 InnerFormValidation
* @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 = InnerForm.normalizeValue(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 if a value is a valid Brazilian state abbreviation (UF).
* @function validateUF
* @memberof InnerFormValidation
* @param {string} value - The UF string to validate (e.g., "SP", "RJ")
* @returns {boolean} True if the value is a valid UF, false otherwise
* @see https://en.wikipedia.org/wiki/States_of_Brazil
*/
InnerForm.validateUF = function (value) {
value = InnerForm.normalizeValue(value);
var ufsValidas = [
"AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA",
"MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN",
"RS", "RO", "RR", "SC", "SP", "SE", "TO"
];
var ufDigitada = value.trim().toUpperCase();
return ufsValidas.includes(ufDigitada);
};
/**
* Validates a Brazilian OAB registration number in the format NUMERIC(1-6) + UF.
* Accepts raw values (511061SP) or formatted values (511.061/SP).
* @function validateOAB
* @memberof InnerFormValidation
* @param {string} value - The OAB number to validate (e.g., "511061SP", "511.061/SP")
* @returns {boolean} True if the OAB is valid, false otherwise
*/
InnerForm.validateOAB = function (value) {
value = InnerForm.normalizeValue(value);
var clean = value.trim().toUpperCase().replace(/[^0-9A-Z]/g, "");
// Debe terminar con UF de dois caracteres
if (clean.length < 3) {
return false;
}
var uf = clean.slice(-2);
var num = clean.slice(0, -2);
if (!InnerForm.validateUF(uf)) {
return false;
}
if (!/^[0-9]{1,6}$/.test(num)) {
return false;
}
return true;
};
/**
* Validates latitude coordinate values.
* @function validateLatitude
* @memberof InnerFormValidation
* @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 = InnerForm.normalizeValue(value).trim().replace(',', '.');
if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) return false;
// Verifica se é um número válido
var numValue = Number(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 InnerFormValidation
* @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 = InnerForm.normalizeValue(value).trim().replace(',', '.');
if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) return false;
// Verifica se é um número válido
var numValue = Number(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 InnerFormValidation
* @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 = InnerForm.normalizeValue(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);
};
/**
* Parses a resolution string in the format "WIDTHxHEIGHT" (e.g. "1024x768").
* Accepts any number of digits on each side (no fixed length) and both
* lowercase/uppercase "x" (also the "×" sign). Optional spaces around
* the separator are ignored.
* @function parseResolution
* @memberof InnerFormValidation
* @param {string} value - The resolution string to parse
* @returns {{width:number,height:number,orientation:string}|null} Parsed dimensions with orientation ("landscape", "portrait" or "square"), or null if invalid
*/
InnerForm.parseResolution = function (value) {
value = InnerForm.normalizeValue(value).trim().replace(/×/g, "x").replace(/X/g, "x");
var match = /^(\d+)\s*x\s*(\d+)$/.exec(value);
if (!match) return null;
var width = parseInt(match[1], 10);
var height = parseInt(match[2], 10);
if (!isFinite(width) || !isFinite(height) || width <= 0 || height <= 0) return null;
return {
width: width,
height: height,
orientation: width > height ? "landscape" : (height > width ? "portrait" : "square")
};
};
/**
* Validates a resolution string in the format "WIDTHxHEIGHT" (e.g. "1024x768").
* There is no digit limit on either side. When the field carries the
* auxiliary class .landscape, width must be greater than height; with
* .portrait, height must be greater than width (square is invalid in both).
* @function validateResolution
* @memberof InnerFormValidation
* @param {string} value - The resolution string to validate
* @param {*} [element] - Optional field/selector used to detect .landscape/.portrait
* @returns {boolean} True if the resolution is valid, false otherwise
*/
InnerForm.validateResolution = function (value, element) {
var parsed = InnerForm.parseResolution(value);
if (!parsed) return false;
var needLandscape = false;
var needPortrait = false;
if (element !== undefined && element !== null) {
try {
needLandscape = InnerForm(element).is(".landscape");
needPortrait = InnerForm(element).is(".portrait");
} catch (e) {
needLandscape = false;
needPortrait = false;
}
}
if (needLandscape && needPortrait) return true;
if (needLandscape) return parsed.width > parsed.height;
if (needPortrait) return parsed.height > parsed.width;
return true;
};
/**
* Parses an aspect ratio string in the format "W:H" (e.g. "16:9").
* Accepts any number of digits on each side (no fixed length).
* Optional spaces around the separator are ignored.
* @function parseAspectRatio
* @memberof InnerFormValidation
* @param {string} value - The aspect ratio string to parse
* @returns {{width:number,height:number,orientation:string}|null} Parsed ratio with orientation ("landscape", "portrait" or "square"), or null if invalid
*/
InnerForm.parseAspectRatio = function (value) {
value = InnerForm.normalizeValue(value).trim();
var match = /^(\d+)\s*:\s*(\d+)$/.exec(value);
if (!match) return null;
var width = parseInt(match[1], 10);
var height = parseInt(match[2], 10);
if (!isFinite(width) || !isFinite(height) || width <= 0 || height <= 0) return null;
return {
width: width,
height: height,
orientation: width > height ? "landscape" : (height > width ? "portrait" : "square")
};
};
/**
* Validates an aspect ratio string in the format "W:H" (e.g. "16:9").
* There is no digit limit on either side. When the field carries the
* auxiliary class .landscape, width must be greater than height; with
* .portrait, height must be greater than width (square is invalid in both).
* @function validateAspectRatio
* @memberof InnerFormValidation
* @param {string} value - The aspect ratio string to validate
* @param {*} [element] - Optional field/selector used to detect .landscape/.portrait
* @returns {boolean} True if the aspect ratio is valid, false otherwise
*/
InnerForm.validateAspectRatio = function (value, element) {
var parsed = InnerForm.parseAspectRatio(value);
if (!parsed) return false;
var needLandscape = false;
var needPortrait = false;
if (element !== undefined && element !== null) {
try {
needLandscape = InnerForm(element).is(".landscape");
needPortrait = InnerForm(element).is(".portrait");
} catch (e) {
needLandscape = false;
needPortrait = false;
}
}
if (needLandscape && needPortrait) return true;
if (needLandscape) return parsed.width > parsed.height;
if (needPortrait) return parsed.height > parsed.width;
return true;
};
/**
* Validates that a value contains at least one of the specified characters.
* @function validateAnyChar
* @memberof InnerFormValidation
* @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) {
value = InnerForm.normalizeValue(value);
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 InnerFormValidation
* @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) {
value = InnerForm.normalizeValue(value);
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 InnerFormValidation
* @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 InnerFormValidation
* @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) {
value = InnerForm.normalizeValue(value);
var dt = 0;
var d = 0;
var m = 0;
var y = 0;
var comp = value.split(" ")[0].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);
}
if (!Number.isFinite(d) || !Number.isFinite(m) || !Number.isFinite(y) || y < 1) return null;
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 InnerFormValidation
* @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 = InnerForm.normalizeValue(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) {
value = InnerForm.normalizeValue(value);
if (!value) 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) {
value = InnerForm.normalizeValue(value);
if (!value) 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 InnerFormValidation
* @param {string} value - Short month/year range string
* @returns {boolean} True if both month/years are valid and first <= second
*/
InnerForm.validShortMonthYearRange = function (value) {
value = InnerForm.normalizeValue(value);
if (!value) 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 InnerFormValidation
* @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);