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