1/* 2* Input Mask plugin for jquery 3* http://github.com/RobinHerbots/jquery.inputmask 4* Copyright (c) 2010 - 2014 Robin Herbots 5* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) 6* Version: 0.0.0 7*/ 8 9(function ($) { 10 if ($.fn.inputmask === undefined) { 11 12 //helper functions 13 function isInputEventSupported(eventName) { 14 var el = document.createElement('input'), 15 evName = 'on' + eventName, 16 isSupported = (evName in el); 17 if (!isSupported) { 18 el.setAttribute(evName, 'return;'); 19 isSupported = typeof el[evName] == 'function'; 20 } 21 el = null; 22 return isSupported; 23 } 24 25 function isInputTypeSupported(inputType) { 26 var isSupported = inputType == "text" || inputType == "tel"; 27 if (!isSupported) { 28 var el = document.createElement('input'); 29 el.setAttribute("type", inputType); 30 isSupported = el.type === "text"; //apply mask only if the type is not natively supported 31 el = null; 32 } 33 return isSupported; 34 } 35 36 function resolveAlias(aliasStr, options, opts) { 37 var aliasDefinition = opts.aliases[aliasStr]; 38 if (aliasDefinition) { 39 if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias 40 $.extend(true, opts, aliasDefinition); //merge alias definition in the options 41 $.extend(true, opts, options); //reapply extra given options 42 return true; 43 } 44 return false; 45 } 46 47 function generateMaskSet(opts, multi) { 48 var ms = undefined; 49 50 function analyseMask(mask) { 51 var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g, 52 escaped = false; 53 54 function maskToken(isGroup, isOptional, isQuantifier, isAlternator) { 55 this.matches = []; 56 this.isGroup = isGroup || false; 57 this.isOptional = isOptional || false; 58 this.isQuantifier = isQuantifier || false; 59 this.isAlternator = isAlternator || false; 60 this.quantifier = { min: 1, max: 1 }; 61 }; 62 63 //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition} 64 function insertTestDefinition(mtoken, element, position) { 65 var maskdef = opts.definitions[element]; 66 var newBlockMarker = mtoken.matches.length == 0; 67 position = position != undefined ? position : mtoken.matches.length; 68 if (maskdef && !escaped) { 69 maskdef["placeholder"] = $.isFunction(maskdef["placeholder"]) ? maskdef["placeholder"].call(this, opts) : maskdef["placeholder"]; 70 var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0; 71 for (var i = 1; i < maskdef.cardinality; i++) { 72 var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"]; 73 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 }); 74 } 75 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 }); 76 } else { 77 mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element, placeholder: undefined, mask: element }); 78 escaped = false;
79 } 80 } 81 82 var currentToken = new maskToken(), 83 match, 84 m, 85 openenings = [], 86 maskTokens = [], 87 openingToken, 88 currentOpeningToken, 89 alternator, 90 lastMatch; 91 92 while (match = tokenizer.exec(mask)) { 93 m = match[0]; 94 switch (m.charAt(0)) { 95 case opts.optionalmarker.end: 96 // optional closing 97 case opts.groupmarker.end: 98 // Group closing 99 openingToken = openenings.pop(); 100 if (openenings.length > 0) { 101 currentOpeningToken = openenings[openenings.length - 1]; 102 currentOpeningToken["matches"].push(openingToken); 103 if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case 104 alternator = openenings.pop(); 105 for (var mndx = 0; mndx < alternator.matches.length; mndx++) { 106 alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group 107 } 108 if (openenings.length > 0) { 109 currentOpeningToken = openenings[openenings.length - 1]; 110 currentOpeningToken["matches"].push(alternator); 111 } else { 112 currentToken.matches.push(alternator); 113 } 114 } 115 } else { 116 currentToken.matches.push(openingToken); 117 } 118 break; 119 case opts.optionalmarker.start: 120 // optional opening 121 openenings.push(new maskToken(false, true)); 122 break; 123 case opts.groupmarker.start: 124 // Group opening 125 openenings.push(new maskToken(true)); 126 break; 127 case opts.quantifiermarker.start: 128 //Quantifier 129 var quantifier = new maskToken(false, false, true); 130 131 m = m.replace(/[{}]/g, ""); 132 var mq = m.split(","), 133 mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), 134 mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1])); 135 if (mq1 == "*" || mq1 == "+") { 136 mq0 = mq1 == "*" ? 0 : 1; 137 } 138 quantifier.quantifier = { min: mq0, max: mq1 }; 139 if (openenings.length > 0) { 140 var matches = openenings[openenings.length - 1]["matches"]; 141 match = matches.pop(); 142 if (!match["isGroup"]) { 143 var groupToken = new maskToken(true); 144 groupToken.matches.push(match); 145 match = groupToken; 146 } 147 matches.push(match); 148 matches.push(quantifier); 149 } else { 150 match = currentToken.matches.pop(); 151 if (!match["isGroup"]) { 152 var groupToken = new maskToken(true); 153 groupToken.matches.push(match); 154 match = groupToken; 155 } 156 currentToken.matches.push(match); 157 currentToken.matches.push(quantifier); 158 } 159 break; 160 case opts.escapeChar: 161 escaped = true; 162 break; 163 case opts.alternatormarker: 164 if (openenings.length > 0) { 165 currentOpeningToken = openenings[openenings.length - 1]; 166 lastMatch = currentOpeningToken.matches.pop(); 167 } else { 168 lastMatch = currentToken.matches.pop(); 169 } 170 if (lastMatch.isAlternator) { 171 openenings.push(lastMatch); 172 } else { 173 alternator = new maskToken(false, false, false, true); 174 alternator.matches.push(lastMatch); 175 openenings.push(alternator); 176 } 177 break; 178 default: 179 if (openenings.length > 0) { 180 currentOpeningToken = openenings[openenings.length - 1]; 181 if (currentOpeningToken.matches.length > 0) { 182 lastMatch = currentOpeningToken.matches[currentOpeningToken.matches.length - 1]; 183 if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert 184 lastMatch.isGroup = false;
185 insertTestDefinition(lastMatch, opts.groupmarker.start, 0); 186 insertTestDefinition(lastMatch, opts.groupmarker.end); 187 } 188 } 189 insertTestDefinition(currentOpeningToken, m); 190 if (currentOpeningToken.isAlternator) { //handle alternator a | b case 191 alternator = openenings.pop(); 192 for (var mndx = 0; mndx < alternator.matches.length; mndx++) { 193 alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group 194 } 195 if (openenings.length > 0) { 196 currentOpeningToken = openenings[openenings.length - 1]; 197 currentOpeningToken["matches"].push(alternator); 198 } else { 199 currentToken.matches.push(alternator); 200 } 201 } 202 } else { 203 if (currentToken.matches.length > 0) { 204 lastMatch = currentToken.matches[currentToken.matches.length - 1]; 205 if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert 206 lastMatch.isGroup = false; 207 insertTestDefinition(lastMatch, opts.groupmarker.start, 0); 208 insertTestDefinition(lastMatch, opts.groupmarker.end); 209 } 210 } 211 insertTestDefinition(currentToken, m); 212 } 213 } 214 } 215 216 if (currentToken.matches.length > 0) { 217 lastMatch = currentToken.matches[currentToken.matches.length - 1]; 218 if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert 219 lastMatch.isGroup = false; 220 insertTestDefinition(lastMatch, opts.groupmarker.start, 0); 221 insertTestDefinition(lastMatch, opts.groupmarker.end); 222 } 223 maskTokens.push(currentToken); 224 } 225 226 //console.log(JSON.stringify(maskTokens)); 227 return maskTokens; 228 } 229 230 function generateMask(mask, metadata) { 231 if (mask == undefined || mask == "") 232 return undefined; 233 else { 234 if (mask.length == 1 && opts.greedy == false && opts.repeat != 0) { 235 opts.placeholder = ""; 236 } //hide placeholder with single non-greedy mask 237 if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") { 238 var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat); 239 mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end; 240 } 241 if ($.inputmask.masksCache[mask] == undefined) { 242 $.inputmask.masksCache[mask] = { 243 "mask": mask, 244 "maskToken": analyseMask(mask), 245 "validPositions": {}, 246 "_buffer": undefined, 247 "buffer": undefined, 248 "tests": {}, 249 "metadata": metadata 250 }; 251 } 252 253 return $.extend(true, {}, $.inputmask.masksCache[mask]); 254 } 255 } 256 function preProcessMask(mask) { 257 mask = mask.toString(); 258 if (opts.numericInput) { //TODO FIX FOR DYNAMIC MASKS WITH QUANTIFIERS 259 mask = mask.split('').reverse(); 260 for (var ndx = 0; ndx < mask.length; ndx++) { 261 if (mask[ndx] == opts.optionalmarker.start) 262 mask[ndx] = opts.optionalmarker.end; 263 else if (mask[ndx] == opts.optionalmarker.end) 264 mask[ndx] = opts.optionalmarker.start; 265 else if (mask[ndx] == opts.groupmarker.start) 266 mask[ndx] = opts.groupmarker.end; 267 else if (mask[ndx] == opts.groupmarker.end) 268 mask[ndx] = opts.groupmarker.start; 269 } 270 mask = mask.join(''); 271 } 272 return mask; 273 } 274 275 if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask 276 opts.mask = opts.mask.call(this, opts); 277 } 278 if ($.isArray(opts.mask)) { 279 if (multi) { //remove me legacy 280 ms = []; 281 $.each(opts.mask, function (ndx, msk) { 282 if (msk["mask"] != undefined && !$.isFunction(msk["mask"])) { 283 ms.push(generateMask(preProcessMask(msk["mask"]), msk)); 284 } else { 285 ms.push(generateMask(preProcessMask(msk), msk)); 286 } 287 }); 288 return ms; 289 } else { 290 if (opts.mask.length > 1) { 291 opts.keepStatic = opts.keepStatic == undefined ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified 292 var altMask = "("; 293 $.each(opts.mask, function (ndx, msk) { 294 if (altMask.length > 1) 295 altMask += ")|("; 296 if (msk["mask"] != undefined && !$.isFunction(msk["mask"])) { 297 altMask += preProcessMask(msk["mask"]); 298 } else { 299 altMask += preProcessMask(msk); 300 } 301 }); 302 altMask += ")"; 303 return generateMask(altMask, opts.mask); 304 } else opts.mask = opts.mask.pop(); 305 } 306 } 307 308 if (opts.mask) { 309 if (opts.mask["mask"] != undefined && !$.isFunction(opts.mask["mask"])) { 310 ms = generateMask(preProcessMask(opts.mask["mask"]), opts.mask); 311 } else { 312 ms = generateMask(preProcessMask(opts.mask), opts.mask); 313 } 314 } 315 316 return ms; 317 } 318 319 var ua = navigator.userAgent, 320 iphone = ua.match(new RegExp("iphone", "i")) !== null, 321 android = ua.match(new RegExp("android.*safari.*", "i")) !== null, 322 androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null, 323 androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null, 324 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), 325 PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange"; 326 327 //if (androidchrome) { 328 // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")), 329 // version = parseInt(new RegExp(/[0-9]+/).exec(browser)); 330 // androidchrome32 = (version == 32); 331 //} 332 333 //masking scope 334 //actionObj definition see below 335 function maskScope(actionObj, maskset, opts) { 336 var isRTL = false, 337 undoValue, 338 compositionValidPos, 339 compositionCaretPos, 340 compositionData, 341 $el, 342 skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround 343 skipInputEvent = false, //skip when triggered from within inputmask 344 ignorable = false, 345 maxLength,
346 firstClick = true; 347 348 //maskset helperfunctions 349 350 351 function getMaskTemplate(baseOnInput, minimalPos, includeInput) { 352 minimalPos = minimalPos || 0; 353 var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos; 354 do { 355 if (baseOnInput === true && getMaskSet()['validPositions'][pos]) { 356 var validPos = getMaskSet()['validPositions'][pos]; 357 test = validPos["match"]; 358 ndxIntlzr = validPos["locator"].slice(); 359 maskTemplate.push(includeInput === true ? validPos["input"] : getPlaceholder(pos, test)); 360 } else { 361 if (minimalPos > pos) { 362 var testPositions = getTests(pos, ndxIntlzr, pos - 1); 363 testPos = testPositions[0]; 364 } else { 365 testPos = getTestTemplate(pos, ndxIntlzr, pos - 1); 366 } 367 test = testPos["match"]; 368 ndxIntlzr = testPos["locator"].slice(); 369 maskTemplate.push(getPlaceholder(pos, test)); 370 } 371 pos++; 372 } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos); 373 maskTemplate.pop(); //drop the last one which is empty 374 return maskTemplate; 375 } 376 function getMaskSet() { 377 return maskset; 378 } 379 function resetMaskSet(soft) { 380 var maskset = getMaskSet(); 381 maskset["buffer"] = undefined; 382 maskset["tests"] = {}; 383 if (soft !== true) { 384 maskset["_buffer"] = undefined; 385 maskset["validPositions"] = {}; 386 maskset["p"] = 0; 387 } 388 } 389 function getLastValidPosition(closestTo) { 390 var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset["validPositions"]; 391 if (closestTo == undefined) closestTo = -1; 392 var before = lastValidPosition, after = lastValidPosition; 393 for (var posNdx in valids) { 394 var psNdx = parseInt(posNdx); 395 if (closestTo == -1 || valids[psNdx]["match"].fn != null) { 396 if (psNdx <= closestTo) before = psNdx; 397 if (psNdx >= closestTo) after = psNdx; 398 } 399 } 400 lastValidPosition = (closestTo - before) > 1 || after < closestTo ? before : after; 401 return lastValidPosition; 402 } 403 function setValidPosition(pos, validTest, fromSetValid) { 404 if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) { 405 //reposition & revalidate others 406 var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]), lvp = getLastValidPosition(), i; 407 for (i = pos; i <= lvp; i++) { //clear selection 408 delete getMaskSet()["validPositions"][i]; 409 } 410 getMaskSet()["validPositions"][pos] = validTest; 411 var valid = true, j; 412 for (i = pos; i <= lvp ; i++) { 413 var t = positionsClone[i]; 414 if (t != undefined) { 415 var vps = getMaskSet()["validPositions"]; 416 if (!opts.keepStatic && vps[i] && (vps[i + 1] != undefined && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || vps[i].alternation != undefined)) 417 j = i + 1; 418 else 419 j = seekNext(i); 420 421 if (positionCanMatchDefinition(j, t["match"].def)) { 422 valid = valid && (isValid(j, t["input"], true, true) !== false); 423 } else valid = t["match"].fn == null; 424 } 425 if (!valid) break; 426 } 427 428 if (!valid) {
429 getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone); 430 return false; 431 } 432 } else 433 getMaskSet()["validPositions"][pos] = validTest; 434 435 return true; 436 } 437 function stripValidPositions(start, end) { 438 var i, startPos = start; 439 if (getMaskSet()["validPositions"][start] != undefined && getMaskSet()["validPositions"][start].input == opts.radixPoint) { 440 end++; 441 startPos++; 442 } 443 for (i = startPos; i < end; i++) { //clear selection 444 if (getMaskSet()["validPositions"][i] != undefined && 445 (getMaskSet()["validPositions"][i].input != opts.radixPoint || i == getLastValidPosition())) 446 delete getMaskSet()["validPositions"][i]; 447 } 448 449 for (i = end ; i <= getLastValidPosition() ;) { 450 var t = getMaskSet()["validPositions"][i]; 451 var s = getMaskSet()["validPositions"][startPos]; 452 if (t != undefined && s == undefined) { 453 if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) { 454 delete getMaskSet()["validPositions"][i]; 455 i++; 456 } 457 startPos++; 458 } else i++; 459 } 460 //remove radixpoint if needed 461 var lvp = getLastValidPosition(); 462 if (start <= lvp && getMaskSet()["validPositions"][lvp] != undefined && (getMaskSet()["validPositions"][lvp].input == opts.radixPoint)) 463 delete getMaskSet()["validPositions"][lvp]; 464 465 resetMaskSet(true); 466 } 467 function getTestTemplate(pos, ndxIntlzr, tstPs) { 468 var testPositions = getTests(pos, ndxIntlzr, tstPs), 469 testPos, 470 lvp = getLastValidPosition(), 471 lvTest = getMaskSet()["validPositions"][lvp] || getTests(0)[0], 472 lvTestAltArr = (lvTest.alternation != undefined) ? lvTest["locator"][lvTest.alternation].split(",") : []; 473 for (var ndx = 0; ndx < testPositions.length; ndx++) { 474 testPos = testPositions[ndx]; 475 476 if (opts.greedy || 477 ((testPos["match"] && (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true) && 478 (lvTest.alternation == undefined || 479 (testPos["locator"][lvTest.alternation] != undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) { 480 break; 481 } 482 } 483 484 return testPos; 485 } 486 function getTest(pos) { 487 if (getMaskSet()['validPositions'][pos]) { 488 return getMaskSet()['validPositions'][pos]["match"]; 489 } 490 return getTests(pos)[0]["match"]; 491 } 492 function positionCanMatchDefinition(pos, def) { 493 var valid = false, tests = getTests(pos); 494 for (var tndx = 0; tndx < tests.length; tndx++) { 495 if (tests[tndx]["match"] && tests[tndx]["match"].def == def) { 496 valid = true; 497 break; 498 } 499 } 500 return valid; 501 }; 502 function getTests(pos, ndxIntlzr, tstPs) { 503 var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false; 504 function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens 505 function handleMatch(match, loopNdx, quantifierRecurse) { 506 if (testPos > 10000) { 507 alert("jquery.inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet()["mask"]); 508 return true; 509 } 510 if (testPos == pos && match.matches == undefined) { 511 matches.push({ "match": match, "locator": loopNdx.reverse() }); 512 return true; 513 } else if (match.matches != undefined) { 514 if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier 515 match = handleMatch(maskToken.matches[tndx + 1], loopNdx); 516 if (match) return true; 517 } else if (match.isOptional) { 518 var optionalToken = match; 519 match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse); 520 if (match) { 521 var latestMatch = matches[matches.length - 1]["match"]; 522 var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0; 523 if (isFirstMatch) { 524 insertStop = true; //insert a stop for non greedy 525 } 526 testPos = pos; //match the position after the group 527 } 528 } else if (match.isAlternator) { 529 var alternateToken = match, malternateMatches = [], maltMatches, 530 currentMatches = matches.slice(), loopNdxCnt = loopNdx.length; 531 var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1; 532 if (altIndex == -1 || typeof altIndex == "string") { 533 var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr; 534 if (typeof altIndex == "string") altIndexArr = altIndex.split(","); 535 for (var amndx = 0;
535 amndx < alternateToken.matches.length; amndx++) { 536 matches = []; 537 match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match; 538 maltMatches = matches.slice(); 539 testPos = currentPos; 540 matches = []; 541 //cloneback 542 for (var i = 0; i < ndxInitializerClone.length; i++) { 543 ndxInitializer[i] = ndxInitializerClone[i]; 544 } 545 //fuzzy merge matches 546 for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) { 547 var altMatch = maltMatches[ndx1]; 548 for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) { 549 var altMatch2 = malternateMatches[ndx2]; 550 //verify equality 551 if (altMatch.match.mask == altMatch2.match.mask && (typeof altIndex != "string" || $.inArray(altMatch.locator[loopNdxCnt].toString(), altIndexArr) != -1)) { 552 maltMatches.splice(ndx1, 1); 553 altMatch2.locator[loopNdxCnt] = altMatch2.locator[loopNdxCnt] + "," + altMatch.locator[loopNdxCnt]; 554 altMatch2.alternation = loopNdxCnt; //we pass the alternation index => used in determineLastRequiredPosition 555 break; 556 } 557 } 558 } 559 malternateMatches = malternateMatches.concat(maltMatches); 560 } 561 562 if (typeof altIndex == "string") { //filter matches 563 malternateMatches = $.map(malternateMatches, function (lmnt, ndx) { 564 if (isFinite(ndx)) { 565 var altLocArr = lmnt.locator[loopNdxCnt].toString().split(","); 566 var mamatch; 567 lmnt.locator[loopNdxCnt] = undefined; 568 lmnt.alternation = undefined; 569 for (var alndx = 0; alndx < altLocArr.length; alndx++) { 570 mamatch = $.inArray(altLocArr[alndx], altIndexArr) != -1; 571 if (mamatch) { //rebuild the locator with valid entries 572 if (lmnt.locator[loopNdxCnt] != undefined) { 573 lmnt.locator[loopNdxCnt] += ","; 574 lmnt.alternation = loopNdxCnt; //only define alternation when there is more then 1 possibility 575 lmnt.locator[loopNdxCnt] += altLocArr[alndx]; 576 } else 577 lmnt.locator[loopNdxCnt] = parseInt(altLocArr[alndx]); 578 } 579 } 580 if (lmnt.locator[loopNdxCnt] != undefined) return lmnt; 581 } 582 }); 583 } 584 585 matches = currentMatches.concat(malternateMatches); 586 //console.log("alternates " + pos + " -> " + JSON.stringify(matches)); 587 insertStop = true; //insert a stopelemnt when there is an alternate 588 } else { 589 match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse); 590 } 591 if (match) return true; 592 } else if (match.isQuantifier && quantifierRecurse !== true) { 593 var qt = match; 594 opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!) 595 for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) { 596 var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1]; 597 match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true); 598 if (match) { 599 //get latest match 600 var latestMatch = matches[matches.length - 1]["match"]; 601 latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1); 602 var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0; 603 604 if (isFirstMatch) { //search for next possible match 605 if (qndx > (qt.quantifier.min - 1)) { 606 insertStop = true; 607 testPos = pos; //match the position after the group 608 break; //stop quantifierloop 609 } else return true; 610 } else { 611 return true; 612 } 613 } 614 } 615 } else { 616 match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse); 617 if (match) 618 return true; 619 } 620 } else testPos++; 621 } 622 623 for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) { 624 if (maskToken.matches[tndx]["isQuantifier"] !== true) { 625 var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse); 626 if (match && testPos == pos) { 627 return match; 628 } else if (testPos > pos) { 629 break; 630 } 631 } 632 } 633 } 634 635 //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) { 636 // return getMaskSet()['tests'][pos]; 637 //} 638 if (ndxIntlzr == undefined) { 639 var previousPos = pos - 1, test; 640 while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) { 641 previousPos--; 642 } 643 if (test != undefined && previousPos > -1) { 644 testPos = previousPos; 645 ndxInitializer = test["locator"].slice(); 646 } else { 647 previousPos = pos - 1; 648 while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) { 649 previousPos--; 650 } 651 if (test != undefined && previousPos > -1) { 652 testPos = previousPos; 653 ndxInitializer = test[0]["locator"].slice(); 654 } 655 } 656 } 657 for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) { 658 var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]); 659 if ((match && testPos == pos) || testPos > pos) { 660 break; 661 } 662 } 663 if (matches.length == 0 || insertStop) 664 matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] }); 665 666 getMaskSet()['tests'][pos] = $.extend(true, [], matches);
666 //set a clone to prevent overwriting some props 667 //console.log(pos + " - " + JSON.stringify(matches)); 668 return getMaskSet()['tests'][pos]; 669 } 670 function getBufferTemplate() { 671 if (getMaskSet()['_buffer'] == undefined) { 672 //generate template 673 getMaskSet()["_buffer"] = getMaskTemplate(false, 1); 674 } 675 return getMaskSet()['_buffer']; 676 } 677 function getBuffer() { 678 if (getMaskSet()['buffer'] == undefined) { 679 getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true); 680 } 681 return getMaskSet()['buffer']; 682 } 683 function refreshFromBuffer(start, end, buffer) { 684 buffer = buffer || getBuffer().slice(); //pass or work on clone 685 if (start === true) { 686 resetMaskSet(); 687 start = 0; 688 end = buffer.length; 689 } else { 690 for (var i = start; i < end; i++) { 691 delete getMaskSet()["validPositions"][i]; 692 delete getMaskSet()["tests"][i]; 693 } 694 } 695 696 for (var i = start; i < end; i++) { 697 if (buffer[i] != opts.skipOptionalPartCharacter) { 698 isValid(i, buffer[i], true, true); 699 } 700 } 701 } 702 function casing(elem, test) { 703 switch (test.casing) { 704 case "upper": 705 elem = elem.toUpperCase(); 706 break; 707 case "lower": 708 elem = elem.toLowerCase(); 709 break; 710 } 711 712 return elem; 713 } 714 function checkAlternationMatch(altArr1, altArr2) { 715 var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), 716 isMatch = false; 717 for (var alndx = 0; alndx < altArr1.length; alndx++) { 718 if ($.inArray(altArr1[alndx], altArrC) != -1) { 719 isMatch = true; 720 break; 721 } 722 } 723 return isMatch; 724 } 725 function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill 726 strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions 727 728 function _isValid(position, c, strict, fromSetValid) { 729 var rslt = false; 730 $.each(getTests(position), function (ndx, tst) { 731 var test = tst["match"]; 732 var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer(); 733 for (var i = test.cardinality; i > loopend; i--) { 734 chrs += getBufferElement(position - (i - 1)); 735 } 736 if (c) { 737 chrs += c; 738 } 739 740 //return is false or a json object => { pos: ??, c: ??} or true 741 rslt = test.fn != null ? 742 test.fn.test(chrs, getMaskSet(), position, strict, opts) 743 : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask 744 { c: test["def"], pos: position } 745 : false; 746 747 if (rslt !== false) { 748 var elem = rslt.c != undefined ? rslt.c : c; 749 elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem; 750 751 var validatedPos = position; 752 if (rslt["remove"] != undefined) { //remove position 753 stripValidPositions(rslt["remove"], rslt["remove"] + 1); 754 } 755 756 if (rslt["refreshFromBuffer"]) { 757 var refresh = rslt["refreshFromBuffer"];
758 strict = true; 759 refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]); 760 if (rslt.pos == undefined && rslt.c == undefined) { 761 rslt.pos = getLastValidPosition(); 762 return false;//breakout if refreshFromBuffer && nothing to insert 763 } 764 validatedPos = rslt.pos != undefined ? rslt.pos : position; 765 if (validatedPos != position) { 766 rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict 767 return false; 768 } 769 770 } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset 771 validatedPos = rslt["pos"]; 772 refreshFromBuffer(position, validatedPos); 773 if (validatedPos != position) { 774 rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict 775 return false; 776 } 777 } 778 779 if (rslt != true && rslt.pos == undefined && rslt.c == undefined) { 780 return false; //breakout if nothing to insert 781 } 782 783 if (ndx > 0) { 784 resetMaskSet(true); 785 } 786 787 if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid)) 788 rslt = false; 789 return false; //break from $.each 790 } 791 }); 792 793 return rslt; 794 } 795 function alternate(pos, c, strict, fromSetValid) { 796 var validPsClone = $.extend(true, {}, getMaskSet()["validPositions"]), 797 lastAlt, 798 alternation; 799 //find last alternation 800 for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) { 801 if (getMaskSet()["validPositions"][lastAlt] && getMaskSet()["validPositions"][lastAlt].alternation != undefined) { 802 alternation = getMaskSet()["validPositions"][lastAlt].alternation; 803 break; 804 } 805 } 806 if (alternation != undefined) { 807 //find first decision making position 808 for (var decisionPos in getMaskSet()["validPositions"]) { 809 if (parseInt(decisionPos) > parseInt(lastAlt) && getMaskSet()["validPositions"][decisionPos].alternation === undefined) { 810 var altPos = getMaskSet()["validPositions"][decisionPos], 811 decisionTaker = altPos.locator[alternation], 812 altNdxs = getMaskSet()["validPositions"][lastAlt].locator[alternation].split(","); 813 814 for (var mndx = 0; mndx < altNdxs.length; mndx++) { 815 if (decisionTaker < altNdxs[mndx]) { 816 var possibilityPos, possibilities; 817 for (var dp = decisionPos - 1; dp >= 0; dp--) { 818 possibilityPos = getMaskSet()["validPositions"][dp]; 819 if (possibilityPos != undefined) { 820 possibilities = possibilityPos.locator[alternation]; //store to reset 821 possibilityPos.locator[alternation] = altNdxs[mndx]; 822 break; 823 } 824 } 825 if (decisionTaker != possibilityPos.locator[alternation]) { 826 var buffer = getBuffer().slice(); //work on clone 827 for (var i = decisionPos; i < getLastValidPosition() + 1; i++) { 828 delete getMaskSet()["validPositions"][i]; 829 delete getMaskSet()["tests"][i]; 830 } 831 resetMaskSet(true); //clear getbuffer 832 opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength 833 for (var i = decisionPos; i < buffer.length; i++) { 834 if (buffer[i] != opts.skipOptionalPartCharacter) { 835 isValid(getLastValidPosition() + 1, buffer[i], false, true); 836 } 837 } 838 possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete 839 var isValidRslt = isValid(pos, c, strict, fromSetValid); 840 opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength 841 if (!isValidRslt) { 842 resetMaskSet(); 843 getMaskSet()["validPositions"]
843= $.extend(true, {}, validPsClone); 844 } else 845 return isValidRslt; 846 } 847 } 848 } 849 break; 850 } 851 } 852 } 853 return false; 854 } 855 //set alternator choice on previous skipped placeholder positions 856 function trackbackAlternations(originalPos, newPos) { 857 var vp = getMaskSet()["validPositions"][newPos], 858 targetLocator = vp.locator, 859 tll = targetLocator.length; 860 861 for (var ps = originalPos; ps < newPos; ps++) { 862 if (!isMask(ps)) { 863 var tests = getTests(ps), 864 bestMatch = tests[0], equality = -1; 865 $.each(tests, function (ndx, tst) { 866 for (var i = 0; i < tll; i++) { 867 if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(','), targetLocator[i].toString().split(',')) && equality < i) { 868 equality = i; 869 bestMatch = tst; 870 } 871 } 872 }); 873 setValidPosition(ps, $.extend({}, bestMatch, { "input": bestMatch["match"].def }), true) 874 } 875 } 876 } 877 //Check for a nonmask before the pos 878 var buffer = getBuffer(); 879 for (var pndx = pos - 1; pndx > -1; pndx--) { 880 if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx]["match"].fn == null) 881 break; 882 else if (getMaskSet()["validPositions"][pndx] == undefined && (!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) { 883 _isValid(pndx, buffer[pndx], true); 884 } 885 } 886 887 var maskPos = pos; 888 var result = false;
889 890 if (fromSetValid && maskPos >= getMaskLength()) { 891 resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length 892 } 893 if (maskPos < getMaskLength()) { 894 result = _isValid(maskPos, c, strict, fromSetValid); 895 if (!strict && result === false) { 896 var currentPosValid = getMaskSet()["validPositions"][maskPos]; 897 if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) { 898 result = { "caret": seekNext(maskPos) }; 899 } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position? 900 for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) { 901 result = _isValid(nPos, c, strict, fromSetValid); 902 if (result !== false) { 903 trackbackAlternations(maskPos, nPos); 904 maskPos = nPos; 905 break; 906 } 907 } 908 } 909 } 910 } 911 if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic 912 result = alternate(pos, c, strict, fromSetValid); 913 } 914 if (result === true) result = { "pos": maskPos }; 915 return result; 916 } 917 function isMask(pos) { 918 var test = getTest(pos); 919 return test.fn != null ? test.fn : false; 920 } 921 function getMaskLength() { 922 var maskLength; 923 maxLength = $el.prop('maxLength'); 924 if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */ 925 if (opts.greedy == false) { 926 var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp], 927 ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined; 928 for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) { 929 testPos = getTestTemplate(pos, ndxIntlzr, pos - 1); 930 ndxIntlzr = testPos["locator"].slice(); 931 } 932 maskLength = pos; 933 } else 934 maskLength = getBuffer().length; 935 936 return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength; 937 } 938 function seekNext(pos) { 939 var maskL = getMaskLength(); 940 if (pos >= maskL) return maskL; 941 var position = pos; 942 while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) { 943 } 944 return position; 945 } 946 function seekPrevious(pos) { 947 var position = pos; 948 if (position <= 0) return 0; 949 950 while (--position > 0 && !isMask(position)) { 951 }; 952 return position; 953 } 954 function getBufferElement(position) { 955 return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"]; 956 } 957 function writeBuffer(input, buffer, caretPos) { 958 input._valueSet(buffer.join('')); 959 if (caretPos != undefined) { 960 caret(input, caretPos); 961 } 962 } 963 function getPlaceholder(pos, test) { 964 test = test || getTest(pos); 965 return test["placeholder"] != undefined ? test["placeholder"] : (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length)); 966 } 967 function checkVal(input, writeOut, strict, nptvl) { 968 function isTemplateMatch() { 969 var isMatch = false;
970 var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join('').indexOf(charCodes); 971 if (charCodeNdx != -1) { 972 isMatch = true; 973 var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx); 974 for (var i = 0; i < bufferTemplateArr.length; i++) { 975 if (bufferTemplateArr[i] != " ") { 976 isMatch = false; break; 977 } 978 } 979 } 980 981 return isMatch; 982 } 983 var inputValue = nptvl != undefined ? nptvl.slice() : input._valueGet().split(''); 984 resetMaskSet(); 985 getMaskSet()["p"] = seekNext(-1); 986 if (writeOut) input._valueSet(""); //initial clear 987 988 var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(''), matches = inputValue.join('').match(new RegExp(escapeRegex(staticInput), "g")); 989 if (matches && matches.length > 0) { 990 inputValue.splice(0, staticInput.length * matches.length); 991 } 992 993 var charCodes = "", initialNdx = 0; 994 $.each(inputValue, function (ndx, charCode) { 995 var keypress = $.Event("keypress"); 996 keypress.which = charCode.charCodeAt(0); 997 charCodes += charCode; 998 var lvp = getLastValidPosition(), lvTest = getMaskSet()["validPositions"][lvp], nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp); 999 if (!isTemplateMatch() || strict) { 1000 var pos = strict ? ndx : (nextTest["match"].fn == null && nextTest["match"].optionality && (lvp + 1) < getMaskSet()["p"] ? lvp + 1 : getMaskSet()["p"]); 1001 keypressEvent.call(input, keypress, true, false, strict, pos); 1002 initialNdx = pos + 1; 1003 charCodes = ""; 1004 } else { 1005 keypressEvent.call(input, keypress, true, false, true, lvp + 1); 1006 } 1007 1008 }); 1009 if (writeOut) { 1010 var keypressResult = opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts); 1011 handleOnKeyResult(input, keypressResult); 1012 writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined); 1013 } 1014 } 1015 function escapeRegex(str) { 1016 return $.inputmask.escapeRegex.call(this, str); 1017 } 1018 function unmaskedvalue($input) { 1019 if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) { 1020 var umValue = [], vps = getMaskSet()["validPositions"]; 1021 for (var pndx in vps) { 1022 if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) { 1023 umValue.push(vps[pndx]["input"]); 1024 } 1025 } 1026 var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join(''); 1027 var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(''); 1028 if ($.isFunction(opts.onUnMask)) { 1029 unmaskedValue = (opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue); 1030 } 1031 return unmaskedValue; 1032 } else { 1033 return $input[0]._valueGet(); 1034 } 1035 } 1036 function TranslatePosition(pos) { 1037 if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) { 1038 var bffrLght = getBuffer().length; 1039 pos = bffrLght - pos; 1040 } 1041 return pos; 1042 } 1043 function caret(input, begin, end) { 1044 var npt = input.jquery && input.length > 0 ? input[0] : input, range; 1045 if (typeof begin == 'number') { 1046 begin = TranslatePosition(begin);
1047 end = TranslatePosition(end); 1048 end = (typeof end == 'number') ? end : begin; 1049 1050 //store caret for multi scope 1051 var data = $(npt).data('_inputmask') || {}; 1052 data["caret"] = { "begin": begin, "end": end }; 1053 $(npt).data('_inputmask', data); 1054 1055 if (!$(npt).is(":visible")) { 1056 return; 1057 } 1058 1059 var scrollCalc = $(npt).css("font-size").replace("px", "") * end; 1060 npt.scrollLeft = scrollCalc > npt.scrollWidth ? scrollCalc : 0; 1061 if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode 1062 if (npt.setSelectionRange) { 1063 npt.selectionStart = begin; 1064 npt.selectionEnd = end; 1065 1066 } else if (npt.createTextRange) { 1067 range = npt.createTextRange(); 1068 range.collapse(true); 1069 range.moveEnd('character', end); 1070 range.moveStart('character', begin); 1071 range.select(); 1072 } 1073 } else { 1074 var data = $(npt).data('_inputmask'); 1075 if (!$(npt).is(":visible") && data && data["caret"] != undefined) { 1076 begin = data["caret"]["begin"]; 1077 end = data["caret"]["end"]; 1078 } else if (npt.setSelectionRange) { 1079 begin = npt.selectionStart; 1080 end = npt.selectionEnd; 1081 } else if (document.selection && document.selection.createRange) { 1082 range = document.selection.createRange(); 1083 begin = 0 - range.duplicate().moveStart('character', -100000); 1084 end = begin + range.text.length; 1085 } 1086 begin = TranslatePosition(begin); 1087 end = TranslatePosition(end); 1088 return { "begin": begin, "end": end }; 1089 } 1090 } 1091 function determineLastRequiredPosition(returnDefinition) { 1092 var buffer = getBuffer(), bl = buffer.length, 1093 pos, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet()["validPositions"][lvp], 1094 ndxIntlzr = lvTest != undefined ? lvTest["locator"].slice() : undefined, testPos; 1095 for (pos = lvp + 1; pos < buffer.length; pos++) { 1096 testPos = getTestTemplate(pos, ndxIntlzr, pos - 1); 1097 ndxIntlzr = testPos["locator"].slice(); 1098 positions[pos] = $.extend(true, {}, testPos); 1099 } 1100 1101 var lvTestAltArr = lvTest && lvTest.alternation != undefined ? lvTest["locator"][lvTest.alternation].split(",") : []; 1102 for (pos = bl - 1; pos > lvp; pos--) { 1103 testPos = positions[pos]["match"]; 1104 if ((testPos.optionality || 1105 testPos.optionalQuantifier || 1106 (lvTest && lvTest.alternation != undefined && positions[pos]["locator"][lvTest.alternation] != undefined && $.inArray(positions[pos]["locator"][lvTest.alternation].toString(), lvTestAltArr) != -1)) 1107 && buffer[pos] == getPlaceholder(pos, testPos)) { 1108 bl--; 1109 } else break; 1110 } 1111 return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl; 1112 } 1113 function clearOptionalTail(buffer) { 1114 var rl = determineLastRequiredPosition(), lmib = buffer.length - 1; 1115 for (; lmib > rl; lmib--) { 1116 if (isMask(lmib)) break; //fixme ismask is not good enough 1117 } 1118 buffer.splice(rl, lmib + 1 - rl); 1119 } 1120 function isComplete(buffer) { //return true / false / undefined (repeat *) 1121 if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts); 1122 if (opts.repeat == "*") return undefined; 1123 var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition(); 1124 1125 if (lvp == aml) { 1126 if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) { 1127 complete = true; 1128 for (var i = 0; i <= aml; i++) { 1129 var mask = isMask(i); 1130 if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) { 1131 complete = false;
1132 break; 1133 } 1134 } 1135 } 1136 } 1137 return complete; 1138 } 1139 function isSelection(begin, end) { 1140 return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) : 1141 (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode); 1142 } 1143 function installEventRuler(npt) { 1144 var events = $._data(npt).events; 1145 1146 $.each(events, function (eventType, eventHandlers) { 1147 $.each(eventHandlers, function (ndx, eventHandler) { 1148 if (eventHandler.namespace == "inputmask") { 1149 if (eventHandler.type != "setvalue") { 1150 var handler = eventHandler.handler; 1151 eventHandler.handler = function (e) { 1152 //console.log("triggered " + e.type); 1153 if (this.readOnly || this.disabled) 1154 e.preventDefault(); 1155 else { 1156 switch (e.type) { 1157 case "input": 1158 if (skipInputEvent === true) { 1159 skipInputEvent = false; 1160 return e.preventDefault(); 1161 } 1162 break; 1163 case "keydown": 1164 //Safari 5.1.x - modal dialog fires keypress twice workaround 1165 skipKeyPressEvent = false; 1166 break; 1167 case "keypress": 1168 if (skipKeyPressEvent === true) 1169 return e.preventDefault(); 1170 skipKeyPressEvent = true; 1171 1172 break; 1173 case "compositionstart": 1174 break; 1175 case "compositionupdate": 1176 skipInputEvent = true; 1177 break; 1178 case "compositionend": 1179 break; 1180 } 1181 //console.log("executed " + e.type); 1182 return handler.apply(this, arguments); 1183 } 1184 }; 1185 } 1186 } 1187 }); 1188 }); 1189 } 1190 function patchValueProperty(npt) { 1191 var valueGet; 1192 var valueSet; 1193 function PatchValhook(type) { 1194 if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) { 1195 var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; }; 1196 var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) { 1197 elem.value = value; 1198 return elem; 1199 }; 1200 1201 $.valHooks[type] = { 1202 get: function (elem) { 1203 var $elem = $(elem); 1204 if ($elem.data('_inputmask')) { 1205 if ($elem.data('_inputmask')['opts'].autoUnmask) 1206 return $elem.inputmask('unmaskedvalue'); 1207 else { 1208 var result = valhookGet(elem), 1209 inputData = $elem.data('_inputmask'), 1210 maskset = inputData['maskset'], 1211 bufferTemplate = maskset['_buffer']; 1212 bufferTemplate = bufferTemplate ? bufferTemplate.join('') : ''; 1213 return result != bufferTemplate ? result : ''; 1214 } 1215 } else return valhookGet(elem); 1216 }, 1217 set: function (elem, value) { 1218 var $elem = $(elem), inputData = $elem.data('_inputmask'), result; 1219 if (inputData) { 1220 result = valhookSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value); 1221 $elem.triggerHandler('setvalue.inputmask'); 1222 } else { 1223 result = valhookSet(elem, value); 1224 } 1225 return result; 1226 }, 1227 inputmaskpatch: true 1228 }; 1229 } 1230 } 1231 function getter() { 1232 var $self = $(this), inputData = $(this).data('_inputmask'); 1233 if (inputData) { 1234 return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : ''); 1235 } else return valueGet.call(this); 1236 } 1237 function setter(value) { 1238 var inputData = $(this).data('_inputmask'); 1239 if (inputData) { 1240 valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value); 1241 $(this).triggerHandler('setvalue.inputmask'); 1242 } else { 1243 valueSet.call(this, value); 1244 } 1245 } 1246 function InstallNativeValueSetFallback(npt) { 1247 $(npt).bind("mouseenter.inputmask", function (event) { 1248 var $input = $(this), input = this, value = input._valueGet(); 1249 if (value != "" && value != getBuffer().join('')) {
1250 this._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, value, opts) || value) : value); 1251 $input.trigger("setvalue"); 1252 } 1253 }); 1254 //!! the bound handlers are executed in the order they where bound 1255 //reorder the events - the mouseenter event is internally mapped to the mouseover event 1256 var events = $._data(npt).events; 1257 var handlers = events["mouseover"]; 1258 if (handlers) { 1259 var ourHandler = handlers[handlers.length - 1]; 1260 for (var i = handlers.length - 1; i > 0; i--) { 1261 handlers[i] = handlers[i - 1]; 1262 } 1263 handlers[0] = ourHandler; 1264 } 1265 } 1266 1267 if (!npt._valueGet) { 1268 //var valueProperty; 1269 if (Object.getOwnPropertyDescriptor) 1270 var valueProperty = Object.getOwnPropertyDescriptor(npt, "value"); 1271 if (valueProperty && valueProperty.configurable && false) { //experimental for chrome 1272 npt._value = valueProperty.value; 1273 valueGet = function () { 1274 return this._value || ""; 1275 } 1276 valueSet = function (value) { 1277 this._value = value; 1278 this.select(); 1279 this.setRangeText(value); 1280 this.selectionStart = this.selectionEnd; 1281 } 1282 1283 Object.defineProperty(npt, "value", { 1284 get: getter, 1285 set: setter 1286 }); 1287 } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) { 1288 valueGet = npt.__lookupGetter__("value"); 1289 valueSet = npt.__lookupSetter__("value"); 1290 1291 npt.__defineGetter__("value", getter); 1292 npt.__defineSetter__("value", setter); 1293 } else { //jquery.val 1294 valueGet = function () { return npt.value; } 1295 valueSet = function (value) { npt.value = value; } 1296 PatchValhook(npt.type); 1297 InstallNativeValueSetFallback(npt); 1298 } 1299 npt._valueGet = function () { 1300 return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this); 1301 }; 1302 npt._valueSet = function (value) { 1303 valueSet.call(this, isRTL ? value.split('').reverse().join('') : value); 1304 }; 1305 } 1306 } 1307 function handleRemove(input, k, pos) { 1308 function generalize() { 1309 if (opts.keepStatic) { 1310 resetMaskSet(true); 1311 var validInputs = [], 1312 lastAlt; 1313 //find last alternation 1314 for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) { 1315 if (getMaskSet()["validPositions"][lastAlt]) { 1316 if (getMaskSet()["validPositions"][lastAlt].alternation != undefined) { 1317 break; 1318 } 1319 validInputs.push(getMaskSet()["validPositions"][lastAlt].input); 1320 delete getMaskSet()["validPositions"][lastAlt]; 1321 } 1322 } 1323 if (lastAlt > 0) { 1324 while (validInputs.length > 0) { 1325 getMaskSet()["p"] = seekNext(getLastValidPosition()); 1326 var keypress = $.Event("keypress"); 1327 keypress.which = validInputs.pop().charCo
1327deAt(0); 1328 keypressEvent.call(input, keypress, true, false, false, getMaskSet()["p"]); 1329 } 1330 } 1331 } 1332 } 1333 1334 if (opts.numericInput || isRTL) { 1335 if (k == $.inputmask.keyCode.BACKSPACE) 1336 k = $.inputmask.keyCode.DELETE; 1337 else if (k == $.inputmask.keyCode.DELETE) 1338 k = $.inputmask.keyCode.BACKSPACE; 1339 1340 if (isRTL) { 1341 var pend = pos.end; 1342 pos.end = pos.begin; 1343 pos.begin = pend; 1344 } 1345 } 1346 1347 if (k == $.inputmask.keyCode.BACKSPACE && pos.end - pos.begin <= 1) 1348 pos.begin = seekPrevious(pos.begin); 1349 else if (k == $.inputmask.keyCode.DELETE && pos.begin == pos.end) 1350 pos.end++; 1351 1352 stripValidPositions(pos.begin, pos.end); 1353 generalize(); //revert the alternation 1354 1355 var firstMaskedPos = getLastValidPosition(pos.begin); 1356 if (firstMaskedPos < pos.begin) { 1357 if (firstMaskedPos == -1) resetMaskSet(); 1358 getMaskSet()["p"] = seekNext(firstMaskedPos); 1359 } else { 1360 getMaskSet()["p"] = pos.begin; 1361 } 1362 } 1363 //postprocessing of the validpositions according to the buffer manipulations 1364 function handleOnKeyResult(input, keyResult, caretPos) { 1365 if (keyResult && keyResult["refreshFromBuffer"]) { 1366 var refresh = keyResult["refreshFromBuffer"]; 1367 refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], keyResult["buffer"]); 1368 1369 resetMaskSet(true); 1370 if (caretPos != undefined) { 1371 writeBuffer(input, getBuffer()); 1372 caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end); 1373 } 1374 } 1375 } 1376 function keydownEvent(e) { 1377 var input = this, $input = $(input), k = e.keyCode, pos = caret(input); 1378 1379 //backspace, delete, and escape get special treatment 1380 if (k == $.inputmask.keyCode.BACKSPACE || k == $.inputmask.keyCode.DELETE || (iphone && k == 127) || (e.ctrlKey && k == 88 && !isInputEventSupported("cut"))) { //backspace/delete 1381 e.preventDefault(); //stop default action but allow propagation 1382 if (k == 88) undoValue = getBuffer().join(''); 1383 handleRemove(input, k, pos); 1384 writeBuffer(input, getBuffer(), getMaskSet()["p"]); 1385 if (input._valueGet() == getBufferTemplate().join('')) 1386 $input.trigger('cleared'); 1387 1388 if (opts.showTooltip) { //update tooltip 1389 $input.prop("title", getMaskSet()["mask"]); 1390 } 1391 } else if (k == $.inputmask.keyCode.END || k == $.inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch 1392 setTimeout(function () { 1393 var caretPos = seekNext(getLastValidPosition()); 1394 if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--; 1395 caret(input, e.shiftKey ? pos.begin : caretPos, caretPos); 1396 }, 0); 1397 } else if ((k == $.inputmask.keyCode.HOME && !e.shiftKey) || k == $.inputmask.keyCode.PAGE_UP) { //Home or page_up 1398 caret(input, 0, e.shiftKey ? pos.begin : 0); 1399 } else if ((opts.undoOnEscape && k == $.inputmask.keyCode.ESCAPE) || (k == 90 && e.ctrlKey)) { //escape && undo 1400 checkVal(input, true, false, undoValue.split('')); 1401 $input.click(); 1402 } else if (k == $.inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert 1403 opts.insertMode = !opts.insertMode; 1404 caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin); 1405 } else if (opts.insertMode == false && !e.shiftKey) { 1406 if (k == $.inputmask.keyCode.RIGHT) { 1407 setTimeout(function () { 1408 var caretPos = caret(input); 1409 caret(input, caretPos.begin); 1410 }, 0); 1411 } else if (k == $.inputmask.keyCode.LEFT) { 1412 setTimeout(function () { 1413 var caretPos = caret(input); 1414 caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1); 1415 }, 0); 1416 } 1417 } 1418 1419 var currentCaretPos = caret(input);
1420 var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), currentCaretPos.begin, opts); 1421 handleOnKeyResult(input, keydownResult, currentCaretPos); 1422 ignorable = $.inArray(k, opts.ignorables) != -1; 1423 } 1424 function keypressEvent(e, checkval, writeOut, strict, ndx) { 1425 var input = this, $input = $(input); 1426 1427 var k = e.which || e.charCode || e.keyCode; 1428 if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) { 1429 return true; 1430 } else { 1431 if (k) { 1432 //special treat the decimal separator 1433 if (k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44; 1434 var pos = checkval ? { begin: ndx, end: ndx } : caret(input), forwardPosition, c = String.fromCharCode(k); 1435 1436 //should we clear a possible selection?? 1437 var isSlctn = isSelection(pos.begin, pos.end); 1438 if (isSlctn) { 1439 getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid 1440 handleRemove(input, $.inputmask.keyCode.DELETE, pos); 1441 if (!opts.insertMode) { //preserve some space 1442 opts.insertMode = !opts.insertMode; 1443 setValidPosition(pos.begin, strict); 1444 opts.insertMode = !opts.insertMode; 1445 } 1446 isSlctn = !opts.multi; 1447 } 1448 1449 getMaskSet()["writeOutBuffer"] = true; 1450 var p = isRTL && !isSlctn ? pos.end : pos.begin; 1451 var valResult = isValid(p, c, strict); 1452 if (valResult !== false) { 1453 if (valResult !== true) { 1454 p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid 1455 c = valResult.c != undefined ? valResult.c : c; //set new char from isValid 1456 } 1457 resetMaskSet(true); 1458 if (valResult.caret != undefined) 1459 forwardPosition = valResult.caret; 1460 else { 1461 var vps = getMaskSet()["validPositions"]; 1462 if (!opts.keepStatic && (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation != undefined)) 1463 forwardPosition = p + 1; 1464 else 1465 forwardPosition = seekNext(p); 1466 } 1467 getMaskSet()["p"] = forwardPosition; //needed for checkval 1468 } 1469 1470 if (writeOut !== false) { 1471 var self = this; 1472 setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0); 1473 if (getMaskSet()["writeOutBuffer"] && valResult !== false) { 1474 var buffer = getBuffer(); 1475 writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition); 1476 if (checkval !== true) { 1477 setTimeout(function () { //timeout needed for IE 1478 if (isComplete(buffer) === true) 1479 $input.trigger("complete"); 1480 skipInputEvent = true; 1481 $input.trigger("input"); 1482 }, 0); 1483 } 1484 } else if (isSlctn) { 1485 getMaskSet()["buffer"] = undefined;
1486 getMaskSet()["validPositions"] = getMaskSet()["undoPositions"]; 1487 } 1488 } else if (isSlctn) { 1489 getMaskSet()["buffer"] = undefined; 1490 getMaskSet()["validPositions"] = getMaskSet()["undoPositions"]; 1491 } 1492 1493 1494 if (opts.showTooltip) { //update tooltip 1495 $input.prop("title", getMaskSet()["mask"]); 1496 } 1497 1498 if (checkval) { 1499 var keyResult = opts.onKeyPress.call(this, e, getBuffer(), forwardPosition, opts); 1500 if (keyResult && keyResult["refreshFromBuffer"]) { 1501 handleOnKeyResult(input, keyResult); 1502 if (keyResult.caret) { 1503 getMaskSet()["p"] = keyResult.caret; 1504 } 1505 } 1506 } else { 1507 var currentCaretPos = caret(input); 1508 handleOnKeyResult(input, opts.onKeyPress.call(this, e, getBuffer(), currentCaretPos.begin, opts), currentCaretPos); 1509 } 1510 e.preventDefault(); 1511 } 1512 } 1513 } 1514 function keyupEvent(e) { 1515 var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer(); 1516 var currentCaretPos = caret(input); 1517 var keyupResult = opts.onKeyUp.call(this, e, buffer, currentCaretPos.begin, opts); 1518 handleOnKeyResult(input, keyupResult, currentCaretPos); 1519 } 1520 function pasteEvent(e) { 1521 var input = this, $input = $(input), inputValue = input._valueGet(), caretPos = caret(input); 1522 //paste event for IE8 and lower I guess ;-) 1523 if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) { 1524 return true; 1525 } else if (e.type == "paste") { 1526 if (window.clipboardData && window.clipboardData.getData) { // IE 1527 inputValue = inputValue.substr(0, caretPos.begin) + window.clipboardData.getData('Text') + inputValue.substr(caretPos.end, inputValue.length); 1528 } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) { 1529 inputValue = inputValue.substr(0, caretPos.begin) + e.originalEvent.clipboardData.getData('text/plain') + inputValue.substr(caretPos.end, inputValue.length);; 1530 } 1531 } 1532 1533 var pasteValue = $.isFunction(opts.onBeforePaste) ? (opts.onBeforePaste.call(input, inputValue, opts) || inputValue) : inputValue; 1534 checkVal(input, true, false, isRTL ? pasteValue.split('').reverse() : pasteValue.split('')); 1535 $input.click(); 1536 if (isComplete(getBuffer()) === true) 1537 $input.trigger("complete"); 1538 1539 return false; 1540 } 1541 //function mobileInputEvent(e) { 1542 // var input = this; 1543 1544 // //backspace in chrome32 only fires input event - detect & treat 1545 // var caretPos = caret(input), 1546 // currentValue = input._valueGet(); 1547 1548 // currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), ""); 1549 // //correct caretposition for chrome 1550 // if (caretPos.begin > currentValue.length) { 1551 // caret(input, currentValue.length); 1552 // caretPos = caret(input); 1553 // } 1554 // if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin] 1555 // && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin] 1556 // && !isMask(caretPos.begin)) { 1557 // e.keyCode = $.inputmask.keyCode.BACKSPACE; 1558 // keydownEvent.call(input, e); 1559 // } 1560 // e.preventDefault(); 1561 //} 1562 function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail 1563 var input = this; 1564 checkVal(input, true, false); 1565 1566 if (isComplete(getBuffer()) === true) 1567 $(input).trigger("complete"); 1568 1569 e.preventDefault(); 1570 } 1571 function compositionStartEvent(e) { 1572 var input = this; 1573 undoValue = getBuffer().join(''); 1574 if (compositionData == "" || e.originalEvent.data.indexOf(compositionData) != 0) { 1575 compositionCaretPos = caret(input); 1576 } 1577 } 1578 function compositionUpdateEvent(e) { 1579 var input = this, caretPos = compositionCaretPos || caret(input); 1580 if (e.originalEvent.data.indexOf(compositionData) == 0) { 1581 resetMaskSet(); 1582 caretPos = { begin: 0, end: 0 }; 1583 } 1584 var newData = e.originalEvent.data; 1585 caret(input, caretPos.begin, caretPos.end); 1586 for (var i = 0; i < newData.length; i++) { 1587 var keypress = $.Event("keypress"); 1588 keypress.which = newData.charCodeAt(i); 1589 skipKeyPressEvent = false;
1590 ignorable = false; 1591 keypressEvent.call(input, keypress); 1592 } 1593 setTimeout(function () { 1594 var forwardPosition = getMaskSet()["p"]; 1595 writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition); 1596 }, 0); 1597 compositionData = e.originalEvent.data; 1598 } 1599 function compositionEndEvent(e) { 1600 //pickup by inputfallback 1601 } 1602 function mask(el) { 1603 $el = $(el); 1604 if ($el.is(":input") && isInputTypeSupported($el.attr("type"))) { 1605 //store tests & original buffer in the input element - used to get the unmasked value 1606 $el.data('_inputmask', { 1607 'maskset': maskset, 1608 'opts': opts, 1609 'isRTL': false 1610 }); 1611 1612 //show tooltip 1613 if (opts.showTooltip) { 1614 $el.prop("title", getMaskSet()["mask"]); 1615 } 1616 1617 if (el.dir == "rtl" || opts.rightAlign) 1618 $el.css("text-align", "right"); 1619 1620 if (el.dir == "rtl" || opts.numericInput) { 1621 el.dir = "ltr"; 1622 $el.removeAttr("dir"); 1623 var inputData = $el.data('_inputmask'); 1624 inputData['isRTL'] = true; 1625 $el.data('_inputmask', inputData); 1626 isRTL = true; 1627 } 1628 1629 //unbind all events - to make sure that no other mask will interfere when re-masking 1630 $el.unbind(".inputmask"); 1631 //bind events 1632 $el.closest('form').bind("submit", function (e) { //trigger change on submit if any 1633 if (undoValue != getBuffer().join('')) { 1634 $el.change(); 1635 } 1636 if ($el[0]._valueGet && $el[0]._valueGet() == getBufferTemplate().join('')) { 1637 $el[0]._valueSet(''); //clear masktemplete on submit and still has focus 1638 } 1639 if (opts.removeMaskOnSubmit) { 1640 $el.inputmask("remove"); 1641 } 1642 }).bind('reset', function () { 1643 setTimeout(function () { 1644 $el.trigger("setvalue"); 1645 }, 0); 1646 }); 1647 $el.bind("mouseenter.inputmask", function () { 1648 var $input = $(this), input = this; 1649 if (!$input.is(":focus") && opts.showMaskOnHover) { 1650 if (input._valueGet() != getBuffer().join('')) { 1651 writeBuffer(input, getBuffer()); 1652 } 1653 } 1654 }).bind("blur.inputmask", function () { 1655 var $input = $(this), input = this; 1656 if ($input.data('_inputmask')) { 1657 var nptValue = input._valueGet(), buffer = getBuffer().slice(); 1658 firstClick = true; 1659 if (undoValue != buffer.join('')) { 1660 $input.change(); 1661 undoValue = buffer.join(''); 1662 } 1663 if (nptValue != '') { 1664 if (opts.clearMaskOnLostFocus) { 1665 if (nptValue == getBufferTemplate().join('')) 1666 buffer = []; 1667 else { //clearout optional tail of the mask 1668 clearOptionalTail(buffer); 1669 } 1670 } 1671 if (isComplete(buffer) === false) { 1672 $input.trigger("incomplete"); 1673 if (opts.clearIncomplete) { 1674 resetMaskSet(); 1675 if (opts.clearMaskOnLostFocus) 1676 buffer = []; 1677 else { 1678 buffer = getBufferTemplate().slice(); 1679 1680 } 1681 } 1682 } 1683 1684 if ($.isFunction(opts.postProcessOnBlur)) { 1685 var keyResult = opts.postProcessOnBlur.call(input, buffer, opts); 1686 if (keyResult) { 1687 handleOnKeyResult(input, keyResult); 1688 buffer = getBuffer(); 1689 } 1690 } 1691 writeBuffer(input, buffer); 1692 } 1693 } 1694 }).bind("focus.inputmask", function (e) { 1695 var $input = $(this), input = this, nptValue = input._valueGet(); 1696 if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) { 1697 if (input._valueGet() != getBuffer().join('')) { 1698 writeBuffer(input, getBuffer(), seekNext(getLastValidPosition())); 1699 } 1700 } 1701 undoValue = getBuffer().join(''); 1702 }).bind("mouseleave.inputmask", function () { 1703 var $input = $(this), input = this; 1704 if (opts.clearMaskOnLostFocus) { 1705 var buffer = getBuffer().slice(), nptValue = input._valueGet(); 1706 if (!$input.is(":focus") && nptValue != $input.attr("placeholder") && nptValue != '') { 1707 if (nptValue == getBufferTemplate().join('')) 1708 buffer = []; 1709 else { //clearout optional tail of the mask 1710 clearOptionalTail(buffer); 1711 } 1712 writeBuffer(input, buffer); 1713 } 1714 } 1715 }).bind("click.inputmask", function () { 1716 var $input = $(this), input = this; 1717 if ($input.is(":focus")) { 1718 var selectedCaret = caret(input); 1719 if (selectedCaret.begin == selectedCaret.end) { 1720 if (opts.radixFocus && opts.radixPoint != "" && $.inArray(opts.radixPoint, getBuffer()) != -1 && (firstClick || getBuffer().join('') == getBufferTemplate().join(''))) { 1721 caret(input, $.inArray(opts.radixPoint, getBuffer())); 1722 firstClick = false;
1723 } else { 1724 var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin, 1725 lastPosition = seekNext(getLastValidPosition(clickPosition)); 1726 if (clickPosition < lastPosition) { 1727 caret(input, isMask(clickPosition) ? clickPosition : seekNext(clickPosition)); 1728 } else { 1729 caret(input, lastPosition); 1730 } 1731 } 1732 } 1733 } 1734 }).bind('dblclick.inputmask', function () { 1735 var input = this; 1736 setTimeout(function () { 1737 caret(input, 0, seekNext(getLastValidPosition())); 1738 }, 0); 1739 }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent 1740 ).bind('setvalue.inputmask', function () { 1741 var input = this; 1742 checkVal(input, true, false); 1743 undoValue = getBuffer().join(''); 1744 if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input._valueGet() == getBufferTemplate().join('')) 1745 input._valueSet(''); 1746 }).bind('cut.inputmask', function (e) { 1747 skipInputEvent = true; //stop inputFallback 1748 var input = this, $input = $(input), pos = caret(input); 1749 1750 handleRemove(input, $.inputmask.keyCode.DELETE, pos); 1751 var keypressResult = opts.onKeyPress.call(this, e, getBuffer(), getMaskSet()["p"], opts); 1752 handleOnKeyResult(input, keypressResult, { begin: getMaskSet()["p"], end: getMaskSet()["p"] }); 1753 if (input._valueGet() == getBufferTemplate().join('')) 1754 $input.trigger('cleared'); 1755 1756 if (opts.showTooltip) { //update tooltip 1757 $input.prop("title", getMaskSet()["mask"]); 1758 } 1759 }).bind('complete.inputmask', opts.oncomplete 1760 ).bind('incomplete.inputmask', opts.onincomplete 1761 ).bind('cleared.inputmask', opts.oncleared); 1762 1763 $el.bind("keydown.inputmask", keydownEvent 1764 ).bind("keypress.inputmask", keypressEvent 1765 ).bind("keyup.inputmask", keyupEvent); 1766 1767 if (!androidfirefox) { 1768 $el.bind("compositionstart.inputmask", compositionStartEvent 1769 ).bind("compositionupdate.inputmask", compositionUpdateEvent 1770 ).bind("compositionend.inputmask", compositionEndEvent); 1771 } 1772 1773 if (PasteEventType === "paste") { 1774 $el.bind("input.inputmask", inputFallBackEvent); 1775 } 1776 1777 //if (android || androidfirefox || androidchrome || kindle) { 1778 // $el.unbind("input.inputmask"); 1779 // $el.bind("input.inputmask", mobileInputEvent); 1780 //} 1781 1782 patchValueProperty(el); 1783 1784 //apply mask 1785 var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el._valueGet(), opts) || el._valueGet()) : el._valueGet(); 1786 checkVal(el, true, false, initialValue.split('')); 1787 var buffer = getBuffer().slice(); 1788 undoValue = buffer.join(''); 1789 // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame. 1790 var activeElement; 1791 try { 1792 activeElement = document.activeElement; 1793 } catch (e) { 1794 } 1795 if (isComplete(buffer) === false) { 1796 if (opts.clearIncomplete) 1797 resetMaskSet(); 1798 } 1799 if (opts.clearMaskOnLostFocus) { 1800 if (buffer.join('') == getBufferTemplate().join('')) { 1801 buffer = []; 1802 } else { 1803 clearOptionalTail(buffer); 1804 } 1805 } 1806 writeBuffer(el, buffer); 1807 if (activeElement === el) { //position the caret when in focus 1808 caret(el, seekNext(getLastValidPosition())); 1809 } 1810 1811 installEventRuler(el); 1812 } 1813 } 1814 1815 //action object 1816 if (actionObj != undefined) { 1817 switch (actionObj["action"]) { 1818 case "isComplete": 1819 $el = $(actionObj["el"]); 1820 maskset = $el.data('_inputmask')['maskset']; 1821 opts = $el.data('_inputmask')['opts']; 1822 return isComplete(actionObj["buffer"]); 1823 case "unmaskedvalue": 1824 $el = actionObj["$input"]; 1825 maskset = $el.data('_inputmask')['maskset']; 1826 opts = $el.data('_inputmask')['opts']; 1827 isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
1828 return unmaskedvalue(actionObj["$input"]); 1829 case "mask": 1830 undoValue = getBuffer().join(''); 1831 mask(actionObj["el"]); 1832 break; 1833 case "format": 1834 $el = $({}); 1835 $el.data('_inputmask', { 1836 'maskset': maskset, 1837 'opts': opts, 1838 'isRTL': opts.numericInput 1839 }); 1840 if (opts.numericInput) { 1841 isRTL = true; 1842 } 1843 var valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj["value"], opts) || actionObj["value"]) : actionObj["value"]).split(''); 1844 checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer); 1845 opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts); 1846 1847 if (actionObj["metadata"]) { 1848 return { 1849 value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''), 1850 metadata: $el.inputmask("getmetadata") 1851 } 1852 } 1853 1854 return isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''); 1855 case "isValid": 1856 $el = $({}); 1857 $el.data('_inputmask', { 1858 'maskset': maskset, 1859 'opts': opts, 1860 'isRTL': opts.numericInput 1861 }); 1862 if (opts.numericInput) { 1863 isRTL = true; 1864 } 1865 var valueBuffer = actionObj["value"].split(''); 1866 checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer); 1867 var buffer = getBuffer(); 1868 var rl = determineLastRequiredPosition(), lmib = buffer.length - 1; 1869 for (; lmib > rl; lmib--) { 1870 if (isMask(lmib)) break; 1871 } 1872 buffer.splice(rl, lmib + 1 - rl); 1873 1874 return isComplete(buffer) && actionObj["value"] == buffer.join(''); 1875 case "getemptymask": 1876 $el = $(actionObj["el"]); 1877 maskset = $el.data('_inputmask')['maskset']; 1878 opts = $el.data('_inputmask')['opts']; 1879 return getBufferTemplate(); 1880 case "remove": 1881 var el = actionObj["el"]; 1882 $el = $(el); 1883 maskset = $el.data('_inputmask')['maskset']; 1884 opts = $el.data('_inputmask')['opts']; 1885 //writeout the unmaskedvalue 1886 el._valueSet(unmaskedvalue($el)); 1887 //unbind all events 1888 $el.unbind(".inputmask"); 1889 //clear data 1890 $el.removeData('_inputmask'); 1891 //restore the value property 1892 var valueProperty; 1893 if (Object.getOwnPropertyDescriptor) 1894 valueProperty = Object.getOwnPropertyDescriptor(el, "value"); 1895 if (valueProperty && valueProperty.get) { 1896 if (el._valueGet) { 1897 Object.defineProperty(el, "value", { 1898 get: el._valueGet, 1899 set: el._valueSet 1900 }); 1901 } 1902 } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) { 1903 if (el._valueGet) { 1904 el.__defineGetter__("value", el._valueGet); 1905 el.__defineSetter__("value", el._valueSet); 1906 } 1907 } 1908 try { //try catch needed for IE7 as it does not supports deleting fns 1909 delete el._valueGet; 1910 delete el._valueSet; 1911 } catch (e) { 1912 el._valueGet = undefined; 1913 el._valueSet = undefined; 1914 1915 } 1916 break; 1917 case "getmetadata": 1918 $el = $(actionObj["el"]); 1919 maskset = $el.data('_inputmask')['maskset']; 1920 opts = $el.data('_inputmask')['opts']; 1921 if ($.isArray(maskset["metadata"])) { 1922 //find last alternation 1923 var alternation, lvp = getLastValidPosition(); 1924 for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) { 1925 if (getMaskSet()["validPositions"][firstAlt] && getMaskSet()["validPositions"][firstAlt].alternation != undefined) { 1926 alternation = getMaskSet()["validPositions"][firstAlt].alternation; 1927 break; 1928 } 1929 } 1930 if (alternation != undefined) { 1931 return maskset["metadata"][getMaskSet()["validPositions"][lvp].locator[alternation]]; 1932 } else return maskset["metadata"][0]; 1933 } 1934 1935 return maskset["metadata"]; 1936 } 1937 } 1938 } 1939 1940 $.inputmask = { 1941 //options default 1942 defaults: { 1943 placeholder: "_", 1944 optionalmarker: { start: "[", end: "]" }, 1945 quantifiermarker: { start: "{", end: "}" }, 1946 groupmarker: { start: "(", end: ")" }, 1947 alternatormarker: "|", 1948 escapeChar: "\\", 1949 mask: null, 1950 oncomplete: $.noop, //executes when the mask is complete 1951 onincomplete: $.noop, //executes when the mask is incomplete and focus is lost 1952 oncleared: $.noop, //executes when the mask is cleared 1953 repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer 1954 greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed 1955 autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor 1956 removeMaskOnSubmit: false, //remove the mask before submitting the form. 1957 clearMaskOnLostFocus: true, 1958 insertMode: true, //insert the input or overwrite the input 1959 clearIncomplete: false, //clear the incomplete input on blur 1960 aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js 1961 alias: null, 1962 onKeyUp: $.noop, //callback to implement autocomplete on certain keys for example 1963 onKeyPress: $.noop, //callback to implement autocomplete on certain keys for example 1964 onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example 1965 onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue 1966 onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue 1967 onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts 1968 showMaskOnFocus: true, //show the mask-placeholder when the input has focus 1969 showMaskOnHover: true, //show the mask-placeholder when hovering the empty input 1970 onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts 1971 skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask 1972 showTooltip: false, //show the activemask as tooltip 1973 numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position) 1974 rightAlign: false, //align to the right 1975 undoOnEscape: true, //pressing escape reverts the value to the value before focus 1976 //numeric basic properties 1977 radixPoint: "", //".", // | "," 1978 radixFocus: false, //position caret to radixpoint on initial click 1979 //numeric basic properties
1980 nojumps: false, //do not jump over fixed parts in the mask 1981 nojumpsThreshold: 0, //start nojumps as of 1982 keepStatic: undefined, //try to keep the mask static while typing. Decisions to alter the mask will be posponed if possible - undefined see auto selection for multi masks 1983 definitions: { 1984 '9': { 1985 validator: "[0-9]", 1986 cardinality: 1, 1987 definitionSymbol: "*" 1988 }, 1989 'a': { 1990 validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]", 1991 cardinality: 1, 1992 definitionSymbol: "*" 1993 }, 1994 '*': { 1995 validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]", 1996 cardinality: 1 1997 } 1998 }, 1999 //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF 2000 ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123], 2001 isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false 2002 postProcessOnBlur: undefined //do some postprocessing of the value on the blur event, args => tmpBuffer, opts 2003 }, 2004 keyCode: { 2005 ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, 2006 NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 2007 }, 2008 masksCache: {}, 2009 escapeRegex: function (str) { 2010 var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; 2011 return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1'); 2012 }, 2013 format: function (value, options, metadata) { 2014 var opts = $.extend(true, {}, $.inputmask.defaults, options); 2015 resolveAlias(opts.alias, options, opts); 2016 return maskScope({ "action": "format", "value": value, "metadata": metadata }, generateMaskSet(opts), opts); 2017 }, 2018 isValid: function (value, options) { 2019 var opts = $.extend(true, {}, $.inputmask.defaults, options); 2020 resolveAlias(opts.alias, options, opts); 2021 return maskScope({ "action": "isValid", "value": value }, generateMaskSet(opts), opts); 2022 } 2023 }; 2024 2025 $.fn.inputmask = function (fn, options, targetScope, targetData, msk) { 2026 targetScope = targetScope || maskScope; 2027 targetData = targetData || "_inputmask"; 2028 function importAttributeOptions(npt, opts, importedOptionsContainer) { 2029 var $npt = $(npt); 2030 if ($npt.data("inputmask-alias")) { 2031 resolveAlias($npt.data("inputmask-alias"), {}, opts); 2032 } 2033 for (var option in opts) { 2034 var optionData = $npt.data("inputmask-" + option.toLowerCase()); 2035 if (optionData != undefined) { 2036 if (option == "mask" && optionData.indexOf("[") == 0) { 2037 opts[option] = optionData.replace(/[\s[\]]/g, "").split("','"); 2038 opts[option][0] = opts[option][0].replace("'", ""); 2039 opts[option][opts[option].length - 1] = opts[option][opts[option].length - 1].replace("'", ""); 2040 } else 2041 opts[option] = typeof optionData == "boolean" ? optionData : optionData.toString(); 2042 if (importedOptionsContainer) 2043 importedOptionsContainer[option] = opts[option]; 2044 } 2045 } 2046 return opts; 2047 } 2048 var opts = $.extend(true, {}, $.inputmask.defaults, options), 2049 maskset; 2050 2051 if (typeof fn === "string") { 2052 switch (fn) { 2053 case "mask": 2054 //resolve possible aliases given by options 2055 resolveAlias(opts.alias, options, opts); 2056 maskset = generateMaskSet(opts, targetScope !== maskScope); 2057 if (maskset == undefined) { return this; } 2058 2059 return this.each(function () { 2060 targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts)); 2061 }); 2062 case "unmaskedvalue": 2063 var $input = $(this); 2064 if ($input.data(targetData)) { 2065 return targetScope({ "action": "unmaskedvalue", "$input": $input }); 2066 } else return $input.val(); 2067 case "remove": 2068 return this.each(function () { 2069 var $input = $(this); 2070 if ($input.data(targetData)) { 2071 targetScope({ "action": "remove", "el": this }); 2072 } 2073 }); 2074 case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation 2075 if (this.data(targetData)) { 2076 return targetScope({ "action": "getemptymask", "el": this }); 2077 } 2078 else return ""; 2079 case "hasMaskedValue": //check wheter the returned value is masked or not;
2079 currently only works reliable when using jquery.val fn to retrieve the value 2080 return this.data(targetData) ? !this.data(targetData)['opts'].autoUnmask : false; 2081 case "isComplete": 2082 if (this.data(targetData)) { 2083 return targetScope({ "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this }); 2084 } else return true; 2085 case "getmetadata": //return mask metadata if exists 2086 if (this.data(targetData)) { 2087 return targetScope({ "action": "getmetadata", "el": this }); 2088 } 2089 else return undefined; 2090 case "_detectScope": 2091 resolveAlias(opts.alias, options, opts); 2092 if (msk != undefined && !resolveAlias(msk, options, opts) && $.inArray(msk, ["mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope"]) == -1) { 2093 opts.mask = msk; 2094 } 2095 if ($.isFunction(opts.mask)) { 2096 opts.mask = opts.mask.call(this, opts); 2097 } 2098 return $.isArray(opts.mask); 2099 default: 2100 resolveAlias(opts.alias, options, opts); 2101 //check if the fn is an alias 2102 if (!resolveAlias(fn, options, opts)) { 2103 //maybe fn is a mask so we try 2104 //set mask 2105 opts.mask = fn; 2106 } 2107 maskset = generateMaskSet(opts, targetScope !== maskScope); 2108 if (maskset == undefined) { return this; } 2109 return this.each(function () { 2110 targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts)); 2111 }); 2112 } 2113 } else if (typeof fn == "object") { 2114 opts = $.extend(true, {}, $.inputmask.defaults, fn); 2115 resolveAlias(opts.alias, fn, opts); //resolve aliases 2116 maskset = generateMaskSet(opts, targetScope !== maskScope); 2117 if (maskset == undefined) { return this; } 2118 return this.each(function () { 2119 targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts)); 2120 }); 2121 } else if (fn == undefined) { 2122 //look for data-inputmask atribute - the attribute should only contain optipns 2123 return this.each(function () { 2124 var attrOptions = $(this).attr("data-inputmask"); 2125 if (attrOptions && attrOptions != "") { 2126 try { 2127 attrOptions = attrOptions.replace(new RegExp("'", "g"), '"'); 2128 var dataoptions = $.parseJSON("{" + attrOptions + "}"); 2129 $.extend(true, dataoptions, options); 2130 opts = $.extend(true, {}, $.inputmask.defaults, dataoptions); 2131 opts = importAttributeOptions(this, opts); 2132 resolveAlias(opts.alias, dataoptions, opts); 2133 opts.alias = undefined; 2134 $(this).inputmask("mask", opts, targetScope); 2135 } catch (ex) { } //need a more relax parseJSON 2136 } 2137 if ($(this).attr("data-inputmask-mask") || $(this).attr("data-inputmask-alias")) { 2138 opts = $.extend(true, {}, $.inputmask.defaults, {}); 2139 var dataOptions = {}; 2140 opts = importAttributeOptions(this, opts, dataOptions); 2141 resolveAlias(opts.alias, dataOptions, opts); 2142 opts.alias = undefined; 2143 $(this).inputmask("mask", opts, targetScope); 2144 } 2145 }); 2146 } 2147 }; 2148 } 2149 return $.fn.inputmask; 2150})(jQuery);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.