forked from rapid7/hackazon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.inputmask.js
1791 lines (1660 loc) · 96.1 KB
/
jquery.inputmask.js
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
/**
* @license Input Mask plugin for jquery
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2014 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 0.0.0
*/
(function ($) {
if ($.fn.inputmask === undefined) {
//helper functions
function isInputEventSupported(eventName) {
var el = document.createElement('input'),
eventName = 'on' + eventName,
isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
function resolveAlias(aliasStr, options, opts) {
var aliasDefinition = opts.aliases[aliasStr];
if (aliasDefinition) {
if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
$.extend(true, opts, aliasDefinition); //merge alias definition in the options
$.extend(true, opts, options); //reapply extra given options
return true;
}
return false;
}
function generateMaskSet(opts, multi) {
var ms = [];
function analyseMask(mask) {
var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
escaped = false;
function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
this.matches = [];
this.isGroup = isGroup || false;
this.isOptional = isOptional || false;
this.isQuantifier = isQuantifier || false;
this.isAlternator = isAlternator || false;
this.quantifier = { min: 1, max: 1 };
};
//test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
function insertTestDefinition(mtoken, element, position) {
var maskdef = opts.definitions[element];
var newBlockMarker = mtoken.matches.length == 0;
position = position != undefined ? position : mtoken.matches.length;
if (maskdef && !escaped) {
var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
for (var i = 1; i < maskdef.cardinality; i++) {
var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
mtoken.matches.splice(position++, 0, { fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element, placeholder: maskdef["placeholder"], mask: element });
}
mtoken.matches.splice(position++, 0, { fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element, placeholder: maskdef["placeholder"], mask: element });
} else {
mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element, placeholder: undefined, mask: element });
escaped = false;
}
}
var currentToken = new maskToken(),
match,
m,
openenings = [],
maskTokens = [],
openingToken;
while (match = tokenizer.exec(mask)) {
m = match[0];
switch (m.charAt(0)) {
case opts.optionalmarker.end:
// optional closing
case opts.groupmarker.end:
// Group closing
openingToken = openenings.pop();
if (openenings.length > 0) {
openenings[openenings.length - 1]["matches"].push(openingToken);
} else {
currentToken.matches.push(openingToken);
}
break;
case opts.optionalmarker.start:
// optional opening
openenings.push(new maskToken(false, true));
break;
case opts.groupmarker.start:
// Group opening
openenings.push(new maskToken(true));
break;
case opts.quantifiermarker.start:
//Quantifier
var quantifier = new maskToken(false, false, true);
m = m.replace(/[{}]/g, "");
var mq = m.split(","),
mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
if (mq1 == "*" || mq1 == "+") {
mq0 = mq1 == "*" ? 0 : 1;
}
quantifier.quantifier = { min: mq0, max: mq1 };
if (openenings.length > 0) {
var matches = openenings[openenings.length - 1]["matches"];
match = matches.pop();
if (!match["isGroup"]) {
var groupToken = new maskToken(true);
groupToken.matches.push(match);
match = groupToken;
}
matches.push(match);
matches.push(quantifier);
} else {
match = currentToken.matches.pop();
if (!match["isGroup"]) {
var groupToken = new maskToken(true);
groupToken.matches.push(match);
match = groupToken;
}
currentToken.matches.push(match);
currentToken.matches.push(quantifier);
}
break;
case opts.escapeChar:
escaped = true;
break;
case opts.alternatormarker:
var alternator = new maskToken(false, false, false, true);
if (openenings.length > 0) {
var matches = openenings[openenings.length - 1]["matches"];
match = matches.pop();
alternator.matches.push(match);
openenings.push(alternator);
} else {
match = currentToken.matches.pop();
alternator.matches.push(match);
openenings.push(alternator);
}
break;
default:
if (openenings.length > 0) {
insertTestDefinition(openenings[openenings.length - 1], m);
var lastToken = openenings[openenings.length - 1];
if (lastToken["isAlternator"]) {
openingToken = openenings.pop();
for (var mndx = 0; mndx < openingToken.matches.length; mndx++) {
openingToken.matches[mndx].isGroup = false; //don't mark alternate groups as group
}
if (openenings.length > 0) {
openenings[openenings.length - 1]["matches"].push(openingToken);
} else {
currentToken.matches.push(openingToken);
}
}
} else {
if (currentToken.matches.length > 0) {
var lastMatch = currentToken.matches[currentToken.matches.length - 1];
if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
lastMatch.isGroup = false;
insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
insertTestDefinition(lastMatch, opts.groupmarker.end);
}
}
insertTestDefinition(currentToken, m);
}
}
}
if (openenings.length > 0) {
var lastToken = openenings[openenings.length - 1];
if (lastToken["isAlternator"]) {
for (var mndx = 0; mndx < lastToken.matches.length; mndx++) {
lastToken.matches[mndx].isGroup = false; //don't mark alternate groups as group
}
}
currentToken.matches = currentToken.matches.concat(openenings);
}
if (currentToken.matches.length > 0) {
var lastMatch = currentToken.matches[currentToken.matches.length - 1];
if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
lastMatch.isGroup = false;
insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
insertTestDefinition(lastMatch, opts.groupmarker.end);
}
maskTokens.push(currentToken);
}
//console.log(JSON.stringify(maskTokens));
return maskTokens;
}
function generateMask(mask, metadata) {
if (opts.numericInput && opts.multi !== true) { //TODO FIX FOR DYNAMIC MASKS WITH QUANTIFIERS
mask = mask.split('').reverse();
for (var ndx = 0; ndx < mask.length; ndx++) {
if (mask[ndx] == opts.optionalmarker.start)
mask[ndx] = opts.optionalmarker.end;
else if (mask[ndx] == opts.optionalmarker.end)
mask[ndx] = opts.optionalmarker.start;
else if (mask[ndx] == opts.groupmarker.start)
mask[ndx] = opts.groupmarker.end;
else if (mask[ndx] == opts.groupmarker.end)
mask[ndx] = opts.groupmarker.start;
}
mask = mask.join('');
}
if (mask == undefined || mask == "")
return undefined;
else {
if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
}
if ($.inputmask.masksCache[mask] == undefined) {
$.inputmask.masksCache[mask] = {
"mask": mask,
"maskToken": analyseMask(mask),
"validPositions": {},
"_buffer": undefined,
"buffer": undefined,
"tests": {},
"metadata": metadata
};
}
return $.extend(true, {}, $.inputmask.masksCache[mask]);
}
}
if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
opts.mask = opts.mask.call(this, opts);
}
if ($.isArray(opts.mask)) {
if (multi) {
$.each(opts.mask, function (ndx, msk) {
if (msk["mask"] != undefined) {
ms.push(generateMask(msk["mask"].toString(), msk));
} else {
ms.push(generateMask(msk.toString()));
}
});
} else {
var altMask = "(" + opts.mask.join(")|(") + ")";
ms = generateMask(altMask);
}
} else {
if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
opts.placeholder = "";
} //hide placeholder with single non-greedy mask
if (opts.mask["mask"] != undefined) {
ms = generateMask(opts.mask["mask"].toString(), opts.mask);
} else {
ms = generateMask(opts.mask.toString());
}
}
return ms;
}
var msie1x = typeof ScriptEngineMajorVersion === "function"
? ScriptEngineMajorVersion() //IE11 detection
: new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
ua = navigator.userAgent,
iphone = ua.match(new RegExp("iphone", "i")) !== null,
android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
kindle = /Kindle/i.test(ua) || /Silk/i.test(ua) || /KFTT/i.test(ua) || /KFOT/i.test(ua) || /KFJWA/i.test(ua) || /KFJWI/i.test(ua) || /KFSOWI/i.test(ua) || /KFTHWA/i.test(ua) || /KFTHWI/i.test(ua) || /KFAPWA/i.test(ua) || /KFAPWI/i.test(ua),
PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
//if (androidchrome) {
// var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
// version = parseInt(new RegExp(/[0-9]+/).exec(browser));
// androidchrome32 = (version == 32);
//}
//masking scope
//actionObj definition see below
function maskScope(actionObj, maskset, opts) {
var isRTL = false,
valueOnFocus,
$el,
skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
skipInputEvent = false, //skip when triggered from within inputmask
ignorable = false,
maxLength;
//maskset helperfunctions
function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
minimalPos = minimalPos || 0;
var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos;
do {
if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
var validPos = getMaskSet()['validPositions'][pos];
test = validPos["match"];
ndxIntlzr = validPos["locator"].slice();
maskTemplate.push(test["fn"] == null ? test["def"] : (includeInput === true ? validPos["input"] : test["placeholder"] || opts.placeholder.charAt(pos % opts.placeholder.length)));
} else {
if (minimalPos > pos) {
var testPositions = getTests(pos, ndxIntlzr, pos - 1);
testPos = testPositions[0];
} else {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
}
test = testPos["match"];
ndxIntlzr = testPos["locator"].slice();
maskTemplate.push(test["fn"] == null ? test["def"] : test["placeholder"] || opts.placeholder.charAt(pos % opts.placeholder.length));
}
pos++;
} while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
maskTemplate.pop(); //drop the last one which is empty
return maskTemplate;
}
function getMaskSet() {
return maskset;
}
function resetMaskSet(soft) {
var maskset = getMaskSet();
maskset["buffer"] = undefined;
maskset["tests"] = {};
if (soft !== true) {
maskset["_buffer"] = undefined;
maskset["validPositions"] = {};
maskset["p"] = -1;
}
}
function getLastValidPosition(closestTo) {
var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset["validPositions"];
if (closestTo == undefined) closestTo = -1;
var before = lastValidPosition, after = lastValidPosition;
for (var posNdx in valids) {
var psNdx = parseInt(posNdx);
if (closestTo == -1 || valids[psNdx]["match"].fn != null) {
if (psNdx < closestTo) before = psNdx;
if (psNdx >= closestTo) after = psNdx;
}
}
lastValidPosition = (closestTo - before) > 1 || after < closestTo ? before : after;
return lastValidPosition;
}
function setValidPosition(pos, validTest, fromSetValid) {
if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
//reposition & revalidate others
var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]), lvp = getLastValidPosition(), i;
for (i = pos; i <= lvp; i++) { //clear selection
delete getMaskSet()["validPositions"][i];
}
getMaskSet()["validPositions"][pos] = validTest;
var valid = true;
for (i = pos; i <= lvp ; i++) {
var t = positionsClone[i];
if (t != undefined) {
var j = t["match"].fn == null ? i + 1 : seekNext(i);
if (positionCanMatchDefinition(j, t["match"].def)) {
valid = valid && isValid(j, t["input"], true, true) !== false;
} else valid = false;
}
if (!valid) break;
}
if (!valid) {
getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
return false;
}
} else
getMaskSet()["validPositions"][pos] = validTest;
return true;
}
function stripValidPositions(start, end) {
var i, startPos = start, lvp;
for (i = start; i < end; i++) { //clear selection
//TODO FIXME BETTER CHECK
delete getMaskSet()["validPositions"][i];
}
for (i = end ; i <= getLastValidPosition() ;) {
var t = getMaskSet()["validPositions"][i];
var s = getMaskSet()["validPositions"][startPos];
if (t != undefined && s == undefined) {
if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) {
delete getMaskSet()["validPositions"][i];
i++;
}
startPos++;
} else i++;
}
lvp = getLastValidPosition();
//catchup
while (lvp > 0 && (getMaskSet()["validPositions"][lvp] == undefined || getMaskSet()["validPositions"][lvp].match.fn == null)) {
delete getMaskSet()["validPositions"][lvp];
lvp--;
}
resetMaskSet(true);
}
function getTestTemplate(pos, ndxIntlzr, tstPs) {
var testPositions = getTests(pos, ndxIntlzr, tstPs), testPos;
for (var ndx = 0; ndx < testPositions.length; ndx++) {
testPos = testPositions[ndx];
if (opts.greedy || (testPos["match"] && (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true)) {
break;
}
}
return testPos;
}
function getTest(pos) {
if (getMaskSet()['validPositions'][pos]) {
return getMaskSet()['validPositions'][pos]["match"];
}
return getTests(pos)[0]["match"];
}
function positionCanMatchDefinition(pos, def) {
var valid = false, tests = getTests(pos);
for (var tndx = 0; tndx < tests.length; tndx++) {
if (tests[tndx]["match"] && tests[tndx]["match"].def == def) {
valid = true;
break;
}
}
return valid;
};
function getTests(pos, ndxIntlzr, tstPs) {
var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
function handleMatch(match, loopNdx, quantifierRecurse) {
if (testPos == pos && match.matches == undefined) {
matches.push({ "match": match, "locator": loopNdx.reverse() });
return true;
} else if (match.matches != undefined) {
if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
if (match) return true;
} else if (match.isOptional) {
var optionalToken = match;
match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
if (match) {
var latestMatch = matches[matches.length - 1]["match"];
var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
if (isFirstMatch) {
insertStop = true; //insert a stop for non greedy
}
testPos = pos; //match the position after the group
}
} else if (match.isAlternator) {
var alternateToken = match;
var currentMatches = matches.slice(), malternate1, malternate2, loopNdxCnt = loopNdx.length;
var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
if (altIndex == -1) {
var currentPos = testPos;
matches = [];
match = ResolveTestFromToken(alternateToken.matches[0], ndxInitializer.slice(), [0].concat(loopNdx), quantifierRecurse);
malternate1 = matches.slice();
testPos = currentPos;
matches = [];
match = ResolveTestFromToken(alternateToken.matches[1], ndxInitializer, [1].concat(loopNdx), quantifierRecurse);
malternate2 = matches.slice();
//fuzzy merge matches
matches = [];
for (var ndx1 = 0; ndx1 < malternate1.length; ndx1++) {
var altMatch = malternate1[ndx1]; currentMatches.push(altMatch);
for (var ndx2 = 0; ndx2 < malternate2.length; ndx2++) {
var altMatch2 = malternate2[ndx2];
//verify equality
if (altMatch.match.mask == altMatch2.match.mask) {
malternate2.splice(ndx2, 1);
altMatch.locator[loopNdxCnt] = -1;
break;
}
}
}
matches = currentMatches.concat(malternate2);
} else {
match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
}
if (match) return true;
} else if (match.isQuantifier && quantifierRecurse !== true) {
var qt = match;
opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!)
for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
if (match) {
//get latest match
var latestMatch = matches[matches.length - 1]["match"];
latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1;
var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
if (isFirstMatch) { //search for next possible match
if (qndx > qt.quantifier.min - 1) {
insertStop = true;
testPos = pos; //match the position after the group
break; //stop quantifierloop
} else return true;
} else {
return true;
}
}
}
} else {
match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
if (match)
return true;
}
} else testPos++;
}
for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
if (maskToken.matches[tndx]["isQuantifier"] !== true) {
var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
if (match && testPos == pos) {
return match;
} else if (testPos > pos) {
break;
}
}
}
}
//if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
// return getMaskSet()['tests'][pos];
//}
if (ndxIntlzr == undefined) {
var previousPos = pos - 1, test;
while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
previousPos--;
}
if (test != undefined && previousPos > -1) {
testPos = previousPos;
ndxInitializer = test["locator"].slice();
} else {
previousPos = pos - 1;
while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
previousPos--;
}
if (test != undefined && previousPos > -1) {
testPos = previousPos;
ndxInitializer = test[0]["locator"].slice();
}
}
}
for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
if ((match && testPos == pos) || testPos > pos) {
break;
}
}
if (matches.length == 0 || insertStop)
matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
getMaskSet()['tests'][pos] = matches;
//console.log(pos + " - " + JSON.stringify(matches));
return matches;
}
function getBufferTemplate() {
if (getMaskSet()['_buffer'] == undefined) {
//generate template
getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
}
return getMaskSet()['_buffer'];
}
function getBuffer() {
if (getMaskSet()['buffer'] == undefined) {
getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
}
return getMaskSet()['buffer'];
}
function refreshFromBuffer(start, end) {
var buffer = getBuffer().slice(); //work on clone
if (start === true) {
resetMaskSet();
start = 0;
end = buffer.length;
} else {
for (var i = start; i < end; i++) {
delete getMaskSet()["validPositions"][i];
delete getMaskSet()["tests"][i];
}
}
for (var i = start; i < end; i++) {
if (buffer[i] != opts.skipOptionalPartCharacter) {
isValid(i, buffer[i], true, true);
}
}
}
function casing(elem, test) {
switch (test.casing) {
case "upper":
elem = elem.toUpperCase();
break;
case "lower":
elem = elem.toLowerCase();
break;
}
return elem;
}
function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
function _isValid(position, c, strict, fromSetValid) {
var rslt = false;
$.each(getTests(position), function (ndx, tst) {
var test = tst["match"];
var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
for (var i = test.cardinality; i > loopend; i--) {
chrs += getBufferElement(position - (i - 1));
}
if (c) {
chrs += c;
}
//return is false or a json object => { pos: ??, c: ??} or true
rslt = test.fn != null ?
test.fn.test(chrs, getMaskSet(), position, strict, opts)
: (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
{ c: test["def"], pos: position }
: false;
if (rslt !== false) {
var elem = rslt.c != undefined ? rslt.c : c;
elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
var validatedPos = position;
if (rslt["remove"] != undefined) { //remove position
stripValidPositions(rslt["remove"], rslt["remove"] + 1);
}
if (rslt["refreshFromBuffer"]) {
var refresh = rslt["refreshFromBuffer"];
strict = true;
refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
if (rslt.pos == undefined && rslt.c == undefined) {
rslt.pos = getLastValidPosition();
return false;//breakout if refreshFromBuffer && nothing to insert
}
validatedPos = rslt.pos != undefined ? rslt.pos : position;
if (validatedPos != position) {
rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
return false;
}
} else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
validatedPos = rslt["pos"];
refreshFromBuffer(position, validatedPos);
if (validatedPos != position) {
rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
return false;
}
}
if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
return false; //breakout if nothing to insert
}
if (ndx > 0) {
resetMaskSet(true);
}
if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid))
rslt = false;
return false; //break from $.each
}
});
return rslt;
}
//Check for a nonmask before the pos
var buffer = getBuffer();
for (var pndx = pos - 1; pndx > -1; pndx--) {
if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx].fn == null)
break;
else if ((!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) {
_isValid(pndx, buffer[pndx], true);
break;
}
}
var maskPos = pos;
if (maskPos >= getMaskLength()) {
// console.log("try alternate match");
return false;
}
var result = _isValid(maskPos, c, strict, fromSetValid);
if (!strict && result === false) {
var currentPosValid = getMaskSet()["validPositions"][maskPos];
if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
result = { "caret": seekNext(maskPos) };
} else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
result = _isValid(nPos, c, strict, fromSetValid);
if (result !== false) {
maskPos = nPos;
break;
}
}
}
}
if (result === true) result = { "pos": maskPos };
return result;
}
function isMask(pos) {
var test = getTest(pos);
return test.fn != null ? test.fn : false;
}
function getMaskLength() {
var maskLength;
maxLength = $el.prop('maxLength');
if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
if (opts.greedy == false) {
var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp],
ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos["locator"].slice();
}
maskLength = pos;
} else
maskLength = getBuffer().length;
return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
}
function seekNext(pos) {
var maskL = getMaskLength();
if (pos >= maskL) return maskL;
var position = pos;
while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
}
return position;
}
function seekPrevious(pos) {
var position = pos;
if (position <= 0) return 0;
while (--position > 0 && !isMask(position)) {
};
return position;
}
function getBufferElement(position) {
return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
}
function writeBuffer(input, buffer, caretPos) {
input._valueSet(buffer.join(''));
if (caretPos != undefined) {
caret(input, caretPos);
}
}
function getPlaceholder(pos, test) {
test = test || getTest(pos);
return test["placeholder"] || (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
}
function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
resetMaskSet();
if (writeOut) input._valueSet(""); //initial clear
$.each(inputValue, function (ndx, charCode) {
if (intelliCheck === true) {
var p = getMaskSet()["p"],
lvp = p == -1 ? p : seekPrevious(p),
pos = lvp == -1 ? ndx : seekNext(lvp);
if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
}
} else {
keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
}
});
if (writeOut) {
var keypressResult = opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
handleOnKeyResult(input, keypressResult);
writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined);
}
}
function escapeRegex(str) {
return $.inputmask.escapeRegex.call(this, str);
}
function truncateInput(inputValue) {
return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
}
function unmaskedvalue($input) {
if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
var umValue = [], vps = getMaskSet()["validPositions"];
for (var pndx in vps) {
if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
umValue.push(vps[pndx]["input"]);
}
}
var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
if ($.isFunction(opts.onUnMask)) {
unmaskedValue = opts.onUnMask.call($input, bufferValue, unmaskedValue, opts);
}
return unmaskedValue;
} else {
return $input[0]._valueGet();
}
}
function TranslatePosition(pos) {
if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
var bffrLght = getBuffer().length;
pos = bffrLght - pos;
}
return pos;
}
function caret(input, begin, end) {
var npt = input.jquery && input.length > 0 ? input[0] : input, range;
if (typeof begin == 'number') {
begin = TranslatePosition(begin);
end = TranslatePosition(end);
end = (typeof end == 'number') ? end : begin;
//store caret for multi scope
var data = $(npt).data('_inputmask') || {};
data["caret"] = { "begin": begin, "end": end };
$(npt).data('_inputmask', data);
if (!$(npt).is(":visible")) {
return;
}
npt.scrollLeft = npt.scrollWidth;
if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
if (npt.setSelectionRange) {
npt.selectionStart = begin;
npt.selectionEnd = end;
} else if (npt.createTextRange) {
range = npt.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
} else {
var data = $(npt).data('_inputmask');
if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
begin = data["caret"]["begin"];
end = data["caret"]["end"];
} else if (npt.setSelectionRange) {
begin = npt.selectionStart;
end = npt.selectionEnd;
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
begin = TranslatePosition(begin);
end = TranslatePosition(end);
return { "begin": begin, "end": end };
}
}
function determineLastRequiredPosition(returnDefinition) {
var buffer = getBuffer(), bl = buffer.length,
pos, lvp = getLastValidPosition(), positions = {},
ndxIntlzr = getMaskSet()["validPositions"][lvp] != undefined ? getMaskSet()["validPositions"][lvp]["locator"].slice() : undefined, testPos;
for (pos = lvp + 1; pos < buffer.length; pos++) {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos["locator"].slice();
positions[pos] = $.extend(true, {}, testPos);
}
for (pos = bl - 1; pos > lvp; pos--) {
testPos = positions[pos]["match"];
if ((testPos.optionality || testPos.optionalQuantifier) && buffer[pos] == getPlaceholder(pos, testPos)) {
bl--;
} else break;
}
return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
}
function clearOptionalTail(input) {
var buffer = getBuffer(), tmpBuffer = buffer.slice();
var rl = determineLastRequiredPosition();
tmpBuffer.length = rl;
writeBuffer(input, tmpBuffer);
}
function isComplete(buffer) { //return true / false / undefined (repeat *)
if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
if (opts.repeat == "*") return undefined;
var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
if (lvp == aml) {
if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
complete = true;
for (var i = 0; i <= aml; i++) {
var mask = isMask(i);
if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
complete = false;
break;
}
}
}
}
return complete;
}
function isSelection(begin, end) {
return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
(end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
}
function installEventRuler(npt) {
var events = $._data(npt).events;
$.each(events, function (eventType, eventHandlers) {
$.each(eventHandlers, function (ndx, eventHandler) {
if (eventHandler.namespace == "inputmask") {
if (eventHandler.type != "setvalue") {
var handler = eventHandler.handler;
eventHandler.handler = function (e) {
if (this.readOnly || this.disabled)
e.preventDefault;
else
return handler.apply(this, arguments);
};
}
}
});
});
}
function patchValueProperty(npt) {
function PatchValhook(type) {
if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
elem.value = value;
return elem;
};
$.valHooks[type] = {
get: function (elem) {
var $elem = $(elem);
if ($elem.data('_inputmask')) {
if ($elem.data('_inputmask')['opts'].autoUnmask)
return $elem.inputmask('unmaskedvalue');
else {
var result = valueGet(elem),
inputData = $elem.data('_inputmask'),
maskset = inputData['maskset'],
bufferTemplate = maskset['_buffer'];
bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
return result != bufferTemplate ? result : '';
}
} else return valueGet(elem);
},
set: function (elem, value) {
var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
if (inputData) {
result = valueSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
$elem.triggerHandler('setvalue.inputmask');
} else {
result = valueSet(elem, value);
}
return result;
},
inputmaskpatch: true
};
}
}
var valueProperty;
if (Object.getOwnPropertyDescriptor)
valueProperty = Object.getOwnPropertyDescriptor(npt, "value");