jquery.inputmask.js 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  1. /**
  2. * @license 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. (function ($) {
  9. if ($.fn.inputmask === undefined) {
  10. //helper functions
  11. function isInputEventSupported(eventName) {
  12. var el = document.createElement('input'),
  13. eventName = 'on' + eventName,
  14. isSupported = (eventName in el);
  15. if (!isSupported) {
  16. el.setAttribute(eventName, 'return;');
  17. isSupported = typeof el[eventName] == 'function';
  18. }
  19. el = null;
  20. return isSupported;
  21. }
  22. function resolveAlias(aliasStr, options, opts) {
  23. var aliasDefinition = opts.aliases[aliasStr];
  24. if (aliasDefinition) {
  25. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  26. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  27. $.extend(true, opts, options); //reapply extra given options
  28. return true;
  29. }
  30. return false;
  31. }
  32. function generateMaskSet(opts) {
  33. var ms = [];
  34. function analyseMask(mask) {
  35. var tokenizer = /(?:[?*+]|\{[0-9]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  36. escaped = false;
  37. function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  38. this.matches = [];
  39. this.isGroup = isGroup || false;
  40. this.isOptional = isOptional || false;
  41. this.isQuantifier = isQuantifier || false;
  42. this.isAlternator = isAlternator || false;
  43. this.quantifier = { min: 1, max: 1 };
  44. };
  45. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
  46. function insertTestDefinition(mtoken, element, position) {
  47. var maskdef = opts.definitions[element];
  48. var newBlockMarker = mtoken.matches.length == 0;
  49. position = position != undefined ? position : mtoken.matches.length;
  50. if (maskdef && !escaped) {
  51. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  52. for (var i = 1; i < maskdef.cardinality; i++) {
  53. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  54. 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 });
  55. }
  56. 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 });
  57. } else {
  58. mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element });
  59. escaped = false;
  60. }
  61. }
  62. var currentToken = new maskToken(),
  63. match,
  64. m,
  65. openenings = [],
  66. maskTokens = [];
  67. while (match = tokenizer.exec(mask)) {
  68. m = match[0];
  69. switch (m.charAt(0)) {
  70. case opts.optionalmarker.end:
  71. // optional closing
  72. case opts.groupmarker.end:
  73. // Group closing
  74. var openingToken = openenings.pop();
  75. if (openenings.length > 0) {
  76. openenings[openenings.length - 1]["matches"].push(openingToken);
  77. } else {
  78. currentToken.matches.push(openingToken);
  79. }
  80. break;
  81. case opts.optionalmarker.start:
  82. // optional opening
  83. openenings.push(new maskToken(false, true));
  84. break;
  85. case opts.groupmarker.start:
  86. // Group opening
  87. openenings.push(new maskToken(true));
  88. break;
  89. case opts.quantifiermarker.start:
  90. //Quantifier
  91. var quantifier = new maskToken(false, false, true);
  92. m = m.replace(/[{}]/g, "");
  93. var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  94. quantifier.quantifier = { min: mq0, max: mq1 };
  95. if (mq1 == "*" || mq1 == "+") opts.greedy = false;
  96. if (openenings.length > 0) {
  97. var matches = openenings[openenings.length - 1]["matches"];
  98. var match = matches.pop();
  99. if (!match["isGroup"]) {
  100. var groupToken = new maskToken(true);
  101. groupToken.matches.push(match);
  102. match = groupToken;
  103. }
  104. matches.push(match);
  105. matches.push(quantifier);
  106. } else {
  107. var match = currentToken.matches.pop();
  108. if (!match["isGroup"]) {
  109. var groupToken = new maskToken(true);
  110. groupToken.matches.push(match);
  111. match = groupToken;
  112. }
  113. currentToken.matches.push(match);
  114. currentToken.matches.push(quantifier);
  115. }
  116. break;
  117. case opts.escapeChar:
  118. escaped = true;
  119. break;
  120. case opts.alternatormarker:
  121. break;
  122. default:
  123. if (openenings.length > 0) {
  124. insertTestDefinition(openenings[openenings.length - 1], m);
  125. } else {
  126. if (currentToken.matches.length > 0) {
  127. var lastMatch = currentToken.matches[currentToken.matches.length - 1];
  128. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  129. lastMatch.isGroup = false;
  130. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  131. insertTestDefinition(lastMatch, opts.groupmarker.end);
  132. }
  133. }
  134. insertTestDefinition(currentToken, m);
  135. }
  136. }
  137. }
  138. if (currentToken.matches.length > 0)
  139. maskTokens.push(currentToken);
  140. //console.log(JSON.stringify(maskTokens));
  141. return maskTokens;
  142. }
  143. function generateMask(mask, metadata) {
  144. if (opts.numericInput) { //TODO FIXME for dynamic masks
  145. mask = mask.split('').reverse().join('');
  146. }
  147. if (mask == undefined || mask == "")
  148. return undefined;
  149. else {
  150. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  151. var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
  152. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  153. }
  154. if ($.inputmask.masksCache[mask] == undefined) {
  155. $.inputmask.masksCache[mask] = {
  156. "mask": mask,
  157. "maskToken": analyseMask(mask),
  158. "validPositions": {},
  159. "_buffer": undefined,
  160. "buffer": undefined,
  161. "tests": {},
  162. "metadata": metadata
  163. };
  164. }
  165. return $.extend(true, {}, $.inputmask.masksCache[mask]);
  166. }
  167. }
  168. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  169. opts.mask = opts.mask.call(this, opts);
  170. }
  171. if ($.isArray(opts.mask)) {
  172. $.each(opts.mask, function (ndx, msk) {
  173. if (msk["mask"] != undefined) {
  174. ms.push(generateMask(msk["mask"].toString(), msk));
  175. } else {
  176. ms.push(generateMask(msk.toString()));
  177. }
  178. });
  179. } else {
  180. if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  181. opts.placeholder = "";
  182. } //hide placeholder with single non-greedy mask
  183. if (opts.mask["mask"] != undefined) {
  184. ms = generateMask(opts.mask["mask"].toString(), opts.mask);
  185. } else {
  186. ms = generateMask(opts.mask.toString());
  187. }
  188. }
  189. return ms;
  190. }
  191. var msie1x = typeof ScriptEngineMajorVersion === "function"
  192. ? ScriptEngineMajorVersion() //IE11 detection
  193. : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
  194. ua = navigator.userAgent,
  195. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  196. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  197. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  198. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  199. 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),
  200. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  201. //if (androidchrome) {
  202. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  203. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  204. // androidchrome32 = (version == 32);
  205. //}
  206. //masking scope
  207. //actionObj definition see below
  208. function maskScope(maskset, opts, actionObj) {
  209. var isRTL = false,
  210. valueOnFocus = getBuffer().join(''),
  211. $el,
  212. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  213. skipInputEvent = false, //skip when triggered from within inputmask
  214. ignorable = false,
  215. maxLength;
  216. //maskset helperfunctions
  217. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  218. minimalPos = minimalPos || 0;
  219. var maskTemplate = [], ndxIntlzr, pos = 0, test;
  220. do {
  221. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  222. var validPos = getMaskSet()['validPositions'][pos];
  223. test = validPos["match"];
  224. ndxIntlzr = validPos["locator"].slice();
  225. maskTemplate.push(test["fn"] == null ? test["def"] : (includeInput === true ? validPos["input"] : opts.placeholder.charAt(pos % opts.placeholder.length)));
  226. } else {
  227. var testPos = getTests(pos, ndxIntlzr, pos - 1), firstMatch = testPos[0]["match"];
  228. testPos = testPos[(minimalPos > pos || (firstMatch.optionalQuantifier !== true && (opts.greedy || (firstMatch.optionality === true && firstMatch.newBlockMarker === false)))) ? 0 : (testPos.length - 1)];
  229. test = testPos["match"];
  230. ndxIntlzr = testPos["locator"].slice();
  231. maskTemplate.push(test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  232. }
  233. pos++;
  234. } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  235. maskTemplate.pop(); //drop the last one which is empty
  236. return maskTemplate;
  237. }
  238. function getMaskSet() {
  239. return maskset;
  240. }
  241. function resetMaskSet(soft) {
  242. var maskset = getMaskSet();
  243. maskset["buffer"] = undefined;
  244. maskset["tests"] = {};
  245. if (soft !== true) {
  246. maskset["_buffer"] = undefined;
  247. maskset["validPositions"] = {};
  248. maskset["p"] = -1;
  249. }
  250. }
  251. function getLastValidPosition(closestTo) { //TODO implement closest to
  252. var maskset = getMaskSet();
  253. var lastValidPosition = -1;
  254. for (var posNdx in maskset["validPositions"]) {
  255. var psNdx = parseInt(posNdx);
  256. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  257. }
  258. return lastValidPosition;
  259. }
  260. function setValidPosition(pos, validTest, strict, fromSetValid) {
  261. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  262. //reposition & revalidate others
  263. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]);
  264. for (var i = seekPrevious(getMaskLength()) ; i > pos && i >= 0; i--) {
  265. if (isMask(i)) {
  266. var j = seekPrevious(i);
  267. var t = getMaskSet()["validPositions"][j];
  268. if (t != undefined) {
  269. if (getTest(i).def == getTest(j).def && getMaskSet()["validPositions"][i] == undefined && isValid(i, t["input"], strict, true) !== false) {
  270. delete getMaskSet()["validPositions"][j];
  271. }
  272. }
  273. }
  274. }
  275. if (getMaskSet()["validPositions"][pos] == undefined) {
  276. getMaskSet()["validPositions"][pos] = validTest;
  277. } else {
  278. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  279. return false;
  280. }
  281. } else
  282. getMaskSet()["validPositions"][pos] = validTest;
  283. return true;
  284. }
  285. function stripValidPositions(start, end) {
  286. var i, ml, startPos = seekNext(start - 1), lvp;
  287. for (i = start; i < end; i++) { //clear selection
  288. delete getMaskSet()["validPositions"][i];
  289. }
  290. for (i = seekNext(end - 1) ; i <= getLastValidPosition() ; i = seekNext(i)) { //clear selection
  291. var t = getMaskSet()["validPositions"][i];
  292. var s = getMaskSet()["validPositions"][startPos];
  293. if (t != undefined && s == undefined) {
  294. if (getTest(startPos).def == t.match.def && isValid(startPos, t["input"], true) !== false) {
  295. delete getMaskSet()["validPositions"][i];
  296. }
  297. startPos = seekNext(startPos);
  298. }
  299. }
  300. var lvp = getLastValidPosition();
  301. //catchup
  302. while (lvp > 0 && (getMaskSet()["validPositions"][lvp] == undefined || getMaskSet()["validPositions"][lvp].match.fn == null)) {
  303. delete getMaskSet()["validPositions"][lvp];
  304. lvp--;
  305. }
  306. resetMaskSet(true);
  307. }
  308. function getTest(pos) {
  309. if (getMaskSet()['validPositions'][pos]) {
  310. return getMaskSet()['validPositions'][pos]["match"];
  311. }
  312. return getTests(pos)[0]["match"];
  313. }
  314. function getTests(pos, ndxIntlzr, tstPs) {
  315. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  316. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  317. function handleMatch(match, loopNdx, quantifierRecurse) {
  318. var currentPos = testPos;
  319. if (testPos == pos && match.matches == undefined) {
  320. matches.push({ "match": match, "locator": loopNdx.reverse() });
  321. return true;
  322. } else if (match.matches != undefined) {
  323. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  324. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  325. if (match) return true;
  326. } else if (match.isOptional) {
  327. var optionalToken = match;
  328. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  329. if (match) {
  330. var latestMatch = matches[matches.length - 1]["match"];
  331. var isFirstMatch = (optionalToken.matches.indexOf(latestMatch) == 0);
  332. if (isFirstMatch) {
  333. insertStop = true; //insert a stop for non greedy
  334. }
  335. //search for next possible match
  336. testPos = currentPos;
  337. }
  338. } else if (match.isAlternator) {
  339. //TODO
  340. } else if (match.isQuantifier && quantifierRecurse !== true) {
  341. var qt = match;
  342. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  343. var tokenGroup = maskToken.matches[maskToken.matches.indexOf(qt) - 1];
  344. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  345. if (match) {
  346. //get latest match
  347. var latestMatch = matches[matches.length - 1]["match"];
  348. if (qndx > qt.quantifier.min - 1) { //mark optionality
  349. latestMatch.optionalQuantifier = true;
  350. }
  351. var isFirstMatch = (tokenGroup.matches.indexOf(latestMatch) == 0);
  352. if (isFirstMatch) { //search for next possible match
  353. if (qndx > qt.quantifier.min - 1) {
  354. insertStop = true;
  355. testPos = pos; //match the position after the group
  356. break; //stop quantifierloop
  357. } else return true;
  358. } else {
  359. return true;
  360. }
  361. }
  362. }
  363. } else {
  364. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  365. if (match)
  366. return true;
  367. }
  368. } else testPos++;
  369. }
  370. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  371. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  372. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  373. if (match && testPos == pos) {
  374. return match;
  375. } else if (testPos > pos) {
  376. break;
  377. }
  378. }
  379. }
  380. }
  381. //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  382. // return getMaskSet()['tests'][pos];
  383. //}
  384. if (ndxIntlzr == undefined) {
  385. var previousPos = pos - 1, test;
  386. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  387. previousPos--;
  388. }
  389. if (test != undefined && previousPos > -1) {
  390. testPos = previousPos;
  391. ndxInitializer = test["locator"].slice();
  392. } else {
  393. previousPos = pos - 1;
  394. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  395. previousPos--;
  396. }
  397. if (test != undefined && previousPos > -1) {
  398. testPos = previousPos;
  399. ndxInitializer = test[0]["locator"].slice();
  400. }
  401. }
  402. }
  403. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  404. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  405. if ((match && testPos == pos) || testPos > pos) {
  406. break;
  407. }
  408. }
  409. if (matches.length == 0 || (insertStop && matches.length < 2))
  410. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  411. getMaskSet()['tests'][pos] = matches;
  412. //console.log(pos + " - " + JSON.stringify(matches));
  413. return matches;
  414. }
  415. function getBufferTemplate() {
  416. if (getMaskSet()['_buffer'] == undefined) {
  417. //generate template
  418. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  419. }
  420. return getMaskSet()['_buffer'];
  421. }
  422. function getBuffer() {
  423. if (getMaskSet()['buffer'] == undefined) {
  424. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  425. }
  426. return getMaskSet()['buffer'];
  427. }
  428. function refreshFromBuffer(start, end) {
  429. var buffer = getBuffer().slice(); //work on clone
  430. for (var i = start; i < end; i++) {
  431. if (buffer[i] != getPlaceholder(i) && buffer[i] != opts.skipOptionalPartCharacter) {
  432. isValid(i, buffer[i], true, true);
  433. }
  434. }
  435. }
  436. function casing(elem, test) {
  437. switch (test.casing) {
  438. case "upper":
  439. elem = elem.toUpperCase();
  440. break;
  441. case "lower":
  442. elem = elem.toLowerCase();
  443. break;
  444. }
  445. return elem;
  446. }
  447. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  448. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  449. function _isValid(position, c, strict, fromSetValid) {
  450. var rslt = false;
  451. $.each(getTests(position), function (ndx, tst) {
  452. var test = tst["match"];
  453. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  454. for (var i = test.cardinality; i > loopend; i--) {
  455. chrs += getBufferElement(position - (i - 1));
  456. }
  457. if (c) {
  458. chrs += c;
  459. }
  460. //return is false or a json object => { pos: ??, c: ??} or true
  461. rslt = test.fn != null ?
  462. test.fn.test(chrs, buffer, position, strict, opts)
  463. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  464. { c: test["def"], pos: position }
  465. : false;
  466. if (rslt !== false) {
  467. var elem = rslt.c != undefined ? rslt.c : c;
  468. elem = elem == opts.skipOptionalPartCharacter ? test["def"] : elem;
  469. var validatedPos = position;
  470. if (rslt["refreshFromBuffer"]) {
  471. var refresh = rslt["refreshFromBuffer"];
  472. strict = true;
  473. if (refresh === true) {
  474. getMaskSet()["validPositions"] = {};
  475. getMaskSet()["tests"] = {};
  476. refreshFromBuffer(0, getBuffer().length);
  477. }
  478. else {
  479. refreshFromBuffer(refresh["start"], refresh["end"]);
  480. }
  481. if (rslt.pos == undefined) {
  482. rslt.pos = getLastValidPosition();
  483. return false;//breakout if refreshFromBuffer && nothing to insert
  484. }
  485. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  486. tst = getTests(validatedPos)[0]; //possible mismatch TODO
  487. } else if (rslt !== true && rslt["pos"] != position) { //their is a position offset
  488. validatedPos = rslt["pos"];
  489. refreshFromBuffer(position, validatedPos);
  490. tst = getTests(validatedPos)[0]; //possible mismatch TODO
  491. }
  492. if (ndx > 0) {
  493. resetMaskSet(true);
  494. }
  495. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), strict, fromSetValid))
  496. rslt = false;
  497. return false; //break from $.each
  498. }
  499. });
  500. return rslt;
  501. }
  502. var maskPos = pos;
  503. var result = _isValid(maskPos, c, strict, fromSetValid);
  504. if (!strict && (opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && result === false && !isMask(maskPos)) { //does the input match on a further position?
  505. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  506. result = _isValid(nPos, c, strict, fromSetValid);
  507. if (result !== false) {
  508. maskPos = nPos;
  509. break;
  510. }
  511. }
  512. }
  513. if (result === true) result = { "pos": maskPos };
  514. return result;
  515. }
  516. function isMask(pos) {
  517. var test = getTest(pos);
  518. return test.fn != null ? test.fn : false;
  519. }
  520. function getMaskLength() {
  521. var maskLength;
  522. maxLength = $el.prop('maxLength');
  523. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  524. if (opts.greedy == false) { //TODO FIXME OPTIMIZE ME
  525. var lvp = getLastValidPosition() + 1,
  526. test = getTest(lvp);
  527. while (!(test.fn == null && test.def == "")) { //determine last possible position
  528. test = getTest(++lvp);
  529. if (test.optionality !== true) {
  530. var tests = getTests(lvp);
  531. test = tests[tests.length - 1]["match"];
  532. }
  533. }
  534. maskLength = getMaskTemplate(true, lvp).length;
  535. getMaskSet()["tests"] = {}; //cleanup tests
  536. } else
  537. maskLength = getBuffer().length;
  538. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  539. }
  540. function seekNext(pos) {
  541. var maskL = getMaskLength();
  542. if (pos >= maskL) return maskL;
  543. var position = pos;
  544. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
  545. }
  546. return position;
  547. }
  548. function seekPrevious(pos) {
  549. var position = pos;
  550. if (position <= 0) return 0;
  551. while (--position > 0 && !isMask(position)) {
  552. };
  553. return position;
  554. }
  555. function getBufferElement(position) {
  556. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  557. }
  558. function writeBuffer(input, buffer, caretPos) {
  559. input._valueSet(buffer.join(''));
  560. if (caretPos != undefined) {
  561. caret(input, caretPos);
  562. }
  563. }
  564. function getPlaceholder(pos) {
  565. var test = getTest(pos);
  566. return test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length);
  567. }
  568. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  569. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  570. resetMaskSet();
  571. if (writeOut) input._valueSet(""); //initial clear
  572. $.each(inputValue, function (ndx, charCode) {
  573. if (intelliCheck === true) {
  574. var p = getMaskSet()["p"],
  575. lvp = p == -1 ? p : seekPrevious(p),
  576. pos = lvp == -1 ? ndx : seekNext(lvp);
  577. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
  578. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  579. }
  580. } else {
  581. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  582. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  583. }
  584. });
  585. }
  586. function escapeRegex(str) {
  587. return $.inputmask.escapeRegex.call(this, str);
  588. }
  589. function truncateInput(inputValue) {
  590. return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
  591. }
  592. function clearOptionalTail(input) {
  593. var buffer = getBuffer(), tmpBuffer = buffer.slice(), pos;
  594. for (pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  595. var test = getTest(pos);
  596. if ((test.optionality || test.optionalQuantifier) && tmpBuffer[pos] == getPlaceholder(pos)) {
  597. tmpBuffer.pop();
  598. } else break;
  599. }
  600. writeBuffer(input, tmpBuffer);
  601. }
  602. function unmaskedvalue($input, skipDatepickerCheck) {
  603. if ($input.data('_inputmask') && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  604. var umValue = $.map(getBuffer(), function (element, index) {
  605. return isMask(index) && isValid(index, element, true) ? element : null;
  606. });
  607. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  608. var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
  609. return $.isFunction(opts.onUnMask) ? opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) : unmaskedValue;
  610. } else {
  611. return $input[0]._valueGet();
  612. }
  613. }
  614. function TranslatePosition(pos) {
  615. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  616. var bffrLght = getBuffer().length;
  617. pos = bffrLght - pos;
  618. }
  619. return pos;
  620. }
  621. function caret(input, begin, end) {
  622. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  623. if (typeof begin == 'number') {
  624. begin = TranslatePosition(begin);
  625. end = TranslatePosition(end);
  626. end = (typeof end == 'number') ? end : begin;
  627. //store caret for multi scope
  628. var data = $(npt).data('_inputmask') || {};
  629. data["caret"] = { "begin": begin, "end": end };
  630. $(npt).data('_inputmask', data);
  631. if (!$(npt).is(':visible')) {
  632. return;
  633. }
  634. npt.scrollLeft = npt.scrollWidth;
  635. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  636. if (npt.setSelectionRange) {
  637. npt.selectionStart = begin;
  638. npt.selectionEnd = end;
  639. } else if (npt.createTextRange) {
  640. range = npt.createTextRange();
  641. range.collapse(true);
  642. range.moveEnd('character', end);
  643. range.moveStart('character', begin);
  644. range.select();
  645. }
  646. } else {
  647. var data = $(npt).data('_inputmask');
  648. if (!$(npt).is(':visible') && data && data["caret"] != undefined) {
  649. begin = data["caret"]["begin"];
  650. end = data["caret"]["end"];
  651. } else if (npt.setSelectionRange) {
  652. begin = npt.selectionStart;
  653. end = npt.selectionEnd;
  654. } else if (document.selection && document.selection.createRange) {
  655. range = document.selection.createRange();
  656. begin = 0 - range.duplicate().moveStart('character', -100000);
  657. end = begin + range.text.length;
  658. }
  659. begin = TranslatePosition(begin);
  660. end = TranslatePosition(end);
  661. return { "begin": begin, "end": end };
  662. }
  663. }
  664. function isComplete(buffer) { //return true / false / undefined (repeat *)
  665. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  666. if (opts.repeat == "*") return undefined;
  667. var complete = false,
  668. aml = seekPrevious(getMaskLength());
  669. if (getLastValidPosition() == aml) {
  670. complete = true;
  671. for (var i = 0; i <= aml; i++) {
  672. var mask = isMask(i);
  673. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  674. complete = false;
  675. break;
  676. }
  677. }
  678. }
  679. return complete;
  680. }
  681. function isSelection(begin, end) {
  682. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  683. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  684. }
  685. function installEventRuler(npt) {
  686. var events = $._data(npt).events;
  687. $.each(events, function (eventType, eventHandlers) {
  688. $.each(eventHandlers, function (ndx, eventHandler) {
  689. if (eventHandler.namespace == "inputmask") {
  690. if (eventHandler.type != "setvalue") {
  691. var handler = eventHandler.handler;
  692. eventHandler.handler = function (e) {
  693. if (this.readOnly || this.disabled)
  694. e.preventDefault;
  695. else
  696. return handler.apply(this, arguments);
  697. };
  698. }
  699. }
  700. });
  701. });
  702. }
  703. function patchValueProperty(npt) {
  704. function PatchValhook(type) {
  705. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  706. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  707. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  708. elem.value = value;
  709. return elem;
  710. };
  711. $.valHooks[type] = {
  712. get: function (elem) {
  713. var $elem = $(elem);
  714. if ($elem.data('_inputmask')) {
  715. if ($elem.data('_inputmask')['opts'].autoUnmask)
  716. return $elem.inputmask('unmaskedvalue');
  717. else {
  718. var result = valueGet(elem),
  719. inputData = $elem.data('_inputmask'),
  720. maskset = inputData['maskset'],
  721. bufferTemplate = maskset['_buffer'];
  722. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  723. return result != bufferTemplate ? result : '';
  724. }
  725. } else return valueGet(elem);
  726. },
  727. set: function (elem, value) {
  728. var $elem = $(elem);
  729. var result = valueSet(elem, value);
  730. if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
  731. return result;
  732. },
  733. inputmaskpatch: true
  734. };
  735. }
  736. }
  737. var valueProperty;
  738. if (Object.getOwnPropertyDescriptor)
  739. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  740. if (valueProperty && valueProperty.get) {
  741. if (!npt._valueGet) {
  742. var valueGet = valueProperty.get;
  743. var valueSet = valueProperty.set;
  744. npt._valueGet = function () {
  745. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  746. };
  747. npt._valueSet = function (value) {
  748. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  749. };
  750. Object.defineProperty(npt, "value", {
  751. get: function () {
  752. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  753. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  754. },
  755. set: function (value) {
  756. valueSet.call(this, value);
  757. $(this).triggerHandler('setvalue.inputmask');
  758. }
  759. });
  760. }
  761. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  762. if (!npt._valueGet) {
  763. var valueGet = npt.__lookupGetter__("value");
  764. var valueSet = npt.__lookupSetter__("value");
  765. npt._valueGet = function () {
  766. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  767. };
  768. npt._valueSet = function (value) {
  769. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  770. };
  771. npt.__defineGetter__("value", function () {
  772. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  773. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  774. });
  775. npt.__defineSetter__("value", function (value) {
  776. valueSet.call(this, value);
  777. $(this).triggerHandler('setvalue.inputmask');
  778. });
  779. }
  780. } else {
  781. if (!npt._valueGet) {
  782. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  783. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  784. }
  785. PatchValhook(npt.type);
  786. }
  787. }
  788. function HandleRemove(input, k, pos) {
  789. if (opts.numericInput || isRTL) {
  790. switch (k) {
  791. case opts.keyCode.BACKSPACE:
  792. k = opts.keyCode.DELETE;
  793. break;
  794. case opts.keyCode.DELETE:
  795. k = opts.keyCode.BACKSPACE;
  796. break;
  797. }
  798. if (isRTL) {
  799. var pend = pos.end;
  800. pos.end = pos.begin;
  801. pos.begin = pend;
  802. }
  803. }
  804. if (pos.begin == pos.end) {
  805. var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
  806. if (opts.isNumeric && opts.radixPoint != "" && getBuffer()[posBegin] == opts.radixPoint) {
  807. pos.begin = (getBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
  808. pos.end = pos.begin;
  809. }
  810. if (k == opts.keyCode.BACKSPACE)
  811. pos.begin = seekPrevious(pos.begin);
  812. else if (k == opts.keyCode.DELETE)
  813. pos.end++;
  814. } else if (pos.end - pos.begin == 1 && !opts.insertMode) {
  815. if (k == opts.keyCode.BACKSPACE)
  816. pos.begin--;
  817. }
  818. stripValidPositions(pos.begin, pos.end);
  819. var firstMaskPos = seekNext(-1);
  820. if (getLastValidPosition() < firstMaskPos) {
  821. getMaskSet()["p"] = firstMaskPos;
  822. } else {
  823. getMaskSet()["p"] = pos.begin;
  824. }
  825. }
  826. function keydownEvent(e) {
  827. //Safari 5.1.x - modal dialog fires keypress twice workaround
  828. skipKeyPressEvent = false;
  829. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  830. //backspace, delete, and escape get special treatment
  831. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  832. e.preventDefault(); //stop default action but allow propagation
  833. if (k == 88) valueOnFocus = getBuffer().join('');
  834. HandleRemove(input, k, pos);
  835. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  836. if (input._valueGet() == getBufferTemplate().join(''))
  837. $input.trigger('cleared');
  838. if (opts.showTooltip) { //update tooltip
  839. $input.prop("title", getMaskSet()["mask"]);
  840. }
  841. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  842. setTimeout(function () {
  843. var caretPos = seekNext(getLastValidPosition());
  844. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  845. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  846. }, 0);
  847. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  848. caret(input, 0, e.shiftKey ? pos.begin : 0);
  849. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  850. checkVal(input, true, false, valueOnFocus.split(''));
  851. $input.click();
  852. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  853. opts.insertMode = !opts.insertMode;
  854. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  855. } else if (opts.insertMode == false && !e.shiftKey) {
  856. if (k == opts.keyCode.RIGHT) {
  857. setTimeout(function () {
  858. var caretPos = caret(input);
  859. caret(input, caretPos.begin);
  860. }, 0);
  861. } else if (k == opts.keyCode.LEFT) {
  862. setTimeout(function () {
  863. var caretPos = caret(input);
  864. caret(input, caretPos.begin - 1);
  865. }, 0);
  866. }
  867. }
  868. var currentCaretPos = caret(input);
  869. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), opts);
  870. if (keydownResult && keydownResult["refreshFromBuffer"] === true) { //extra stuff to execute on keydown
  871. getMaskSet()["validPositions"] = {};
  872. refreshFromBuffer(0, getBuffer().length);
  873. caret(input, currentCaretPos.begin, currentCaretPos.end);
  874. }
  875. ignorable = $.inArray(k, opts.ignorables) != -1;
  876. }
  877. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  878. //Safari 5.1.x - modal dialog fires keypress twice workaround
  879. if (k == undefined && skipKeyPressEvent) return false;
  880. skipKeyPressEvent = true;
  881. var input = this, $input = $(input);
  882. e = e || window.event;
  883. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  884. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  885. return true;
  886. } else {
  887. if (k) {
  888. //special treat the decimal separator
  889. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  890. var pos, forwardPosition, c = String.fromCharCode(k);
  891. if (checkval) {
  892. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  893. pos = { begin: pcaret, end: pcaret };
  894. } else {
  895. pos = caret(input);
  896. }
  897. //should we clear a possible selection??
  898. var isSlctn = isSelection(pos.begin, pos.end);
  899. if (isSlctn) {
  900. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  901. HandleRemove(input, opts.keyCode.DELETE, pos);
  902. if (!opts.insertMode) { //preserve some space
  903. opts.insertMode = !opts.insertMode;
  904. setValidPosition(pos.begin, undefined, strict);
  905. opts.insertMode = !opts.insertMode;
  906. }
  907. isSlctn = !opts.multi;
  908. }
  909. var radixPosition = getBuffer().join('').indexOf(opts.radixPoint);
  910. if (opts.isNumeric && checkval !== true && radixPosition != -1) {
  911. if (opts.greedy && pos.begin <= radixPosition) {
  912. pos.begin = seekPrevious(pos.begin);
  913. pos.end = pos.begin;
  914. } else if (c == opts.radixPoint) {
  915. pos.begin = radixPosition;
  916. pos.end = pos.begin;
  917. }
  918. }
  919. getMaskSet()["writeOutBuffer"] = true;
  920. var p = pos.begin;
  921. var valResult = isValid(p, c, strict);
  922. if (valResult !== false) {
  923. if (valResult !== true) {
  924. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  925. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  926. }
  927. resetMaskSet(true);
  928. forwardPosition = seekNext(p);
  929. getMaskSet()["p"] = forwardPosition; //needed for checkval
  930. }
  931. if (writeOut !== false) {
  932. var self = this;
  933. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  934. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  935. var buffer = getBuffer();
  936. var newCaretPosition;
  937. if (checkval) {
  938. newCaretPosition = undefined;
  939. } else if (opts.numericInput) {
  940. if (p > radixPosition) {
  941. newCaretPosition = seekPrevious(forwardPosition);
  942. } else if (c == opts.radixPoint) {
  943. newCaretPosition = forwardPosition - 1;
  944. } else newCaretPosition = seekPrevious(forwardPosition - 1);
  945. } else {
  946. newCaretPosition = forwardPosition;
  947. }
  948. writeBuffer(input, buffer, newCaretPosition);
  949. if (checkval !== true) {
  950. setTimeout(function () { //timeout needed for IE
  951. if (isComplete(buffer) === true)
  952. $input.trigger("complete");
  953. skipInputEvent = true;
  954. $input.trigger("input");
  955. }, 0);
  956. }
  957. } else if (isSlctn) {
  958. getMaskSet()["buffer"] = undefined;
  959. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  960. }
  961. } else if (isSlctn) {
  962. getMaskSet()["buffer"] = undefined;
  963. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  964. }
  965. if (opts.showTooltip) { //update tooltip
  966. $input.prop("title", getMaskSet()["mask"]);
  967. }
  968. //needed for IE8 and below
  969. if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false;
  970. }
  971. }
  972. }
  973. function keyupEvent(e) {
  974. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  975. var keyupResult = opts.onKeyUp.call(this, e, buffer, opts);
  976. if (keyupResult && keyupResult["refreshFromBuffer"] === true) {
  977. getMaskSet()["validPositions"] = {};
  978. refreshFromBuffer(0, getBuffer().length);
  979. }
  980. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  981. if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  982. resetMaskSet();
  983. buffer = getBuffer();
  984. writeBuffer(input, buffer);
  985. caret(input, 0);
  986. valueOnFocus = getBuffer().join('');
  987. } else {
  988. writeBuffer(input, buffer);
  989. if (buffer.join('') == getBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) {
  990. caret(input, TranslatePosition(0));
  991. $input.click();
  992. } else
  993. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  994. }
  995. }
  996. }
  997. function pasteEvent(e) {
  998. if (skipInputEvent === true && e.type == "input") {
  999. skipInputEvent = false;
  1000. return true;
  1001. }
  1002. var input = this, $input = $(input);
  1003. //paste event for IE8 and lower I guess ;-)
  1004. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1005. return true;
  1006. }
  1007. setTimeout(function () {
  1008. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, input._valueGet(), opts) : input._valueGet();
  1009. checkVal(input, false, false, pasteValue.split(''), true);
  1010. writeBuffer(input, getBuffer());
  1011. if (isComplete(getBuffer()) === true)
  1012. $input.trigger("complete");
  1013. $input.click();
  1014. }, 0);
  1015. }
  1016. function mobileInputEvent(e) {
  1017. var input = this, $input = $(input);
  1018. //backspace in chrome32 only fires input event - detect & treat
  1019. var caretPos = caret(input),
  1020. currentValue = input._valueGet();
  1021. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1022. //correct caretposition for chrome
  1023. if (caretPos.begin > currentValue.length) {
  1024. caret(input, currentValue.length);
  1025. caretPos = caret(input);
  1026. }
  1027. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1028. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1029. && !isMask(caretPos.begin)) {
  1030. e.keyCode = opts.keyCode.BACKSPACE;
  1031. keydownEvent.call(input, e);
  1032. } else { //nonnumerics don't fire keypress
  1033. checkVal(input, false, false, currentValue.split(''));
  1034. writeBuffer(input, getBuffer());
  1035. if (isComplete(getBuffer()) === true)
  1036. $input.trigger("complete");
  1037. $input.click();
  1038. }
  1039. e.preventDefault();
  1040. }
  1041. function mask(el) {
  1042. $el = $(el);
  1043. if ($el.is(":input")) {
  1044. //store tests & original buffer in the input element - used to get the unmasked value
  1045. $el.data('_inputmask', {
  1046. 'maskset': maskset,
  1047. 'opts': opts,
  1048. 'isRTL': false
  1049. });
  1050. //show tooltip
  1051. if (opts.showTooltip) {
  1052. $el.prop("title", getMaskSet()["mask"]);
  1053. }
  1054. patchValueProperty(el);
  1055. if (opts.numericInput) opts.isNumeric = opts.numericInput;
  1056. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1057. $el.css("text-align", "right");
  1058. if (el.dir == "rtl" || opts.numericInput) {
  1059. el.dir = "ltr";
  1060. $el.removeAttr("dir");
  1061. var inputData = $el.data('_inputmask');
  1062. inputData['isRTL'] = true;
  1063. $el.data('_inputmask', inputData);
  1064. isRTL = true;
  1065. }
  1066. //unbind all events - to make sure that no other mask will interfere when re-masking
  1067. $el.unbind(".inputmask");
  1068. $el.removeClass('focus.inputmask');
  1069. //bind events
  1070. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1071. if (valueOnFocus != getBuffer().join('')) {
  1072. $el.change();
  1073. }
  1074. }).bind('reset', function () {
  1075. setTimeout(function () {
  1076. $el.trigger("setvalue");
  1077. }, 0);
  1078. });
  1079. $el.bind("mouseenter.inputmask", function () {
  1080. var $input = $(this), input = this;
  1081. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  1082. if (input._valueGet() != getBuffer().join('')) {
  1083. writeBuffer(input, getBuffer());
  1084. }
  1085. }
  1086. }).bind("blur.inputmask", function () {
  1087. var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getBuffer();
  1088. $input.removeClass('focus.inputmask');
  1089. if (valueOnFocus != getBuffer().join('')) {
  1090. $input.change();
  1091. }
  1092. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1093. if (nptValue == getBufferTemplate().join(''))
  1094. input._valueSet('');
  1095. else { //clearout optional tail of the mask
  1096. clearOptionalTail(input);
  1097. }
  1098. }
  1099. if (isComplete(buffer) === false) {
  1100. $input.trigger("incomplete");
  1101. if (opts.clearIncomplete) {
  1102. resetMaskSet();
  1103. if (opts.clearMaskOnLostFocus)
  1104. input._valueSet('');
  1105. else {
  1106. buffer = getBufferTemplate().slice();
  1107. writeBuffer(input, buffer);
  1108. }
  1109. }
  1110. }
  1111. }).bind("focus.inputmask", function () {
  1112. var $input = $(this), input = this, nptValue = input._valueGet();
  1113. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1114. if (input._valueGet() != getBuffer().join('')) {
  1115. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1116. }
  1117. }
  1118. $input.addClass('focus.inputmask');
  1119. valueOnFocus = getBuffer().join('');
  1120. }).bind("mouseleave.inputmask", function () {
  1121. var $input = $(this), input = this;
  1122. if (opts.clearMaskOnLostFocus) {
  1123. if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1124. if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
  1125. input._valueSet('');
  1126. else { //clearout optional tail of the mask
  1127. clearOptionalTail(input);
  1128. }
  1129. }
  1130. }
  1131. }).bind("click.inputmask", function () {
  1132. var input = this;
  1133. setTimeout(function () {
  1134. var selectedCaret = caret(input), buffer = getBuffer();
  1135. if (selectedCaret.begin == selectedCaret.end) {
  1136. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1137. lvp = getLastValidPosition(clickPosition),
  1138. lastPosition;
  1139. if (opts.isNumeric) {
  1140. lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
  1141. (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
  1142. seekNext(lvp);
  1143. } else {
  1144. lastPosition = seekNext(lvp);
  1145. }
  1146. if (clickPosition < lastPosition) {
  1147. if (isMask(clickPosition))
  1148. caret(input, clickPosition);
  1149. else caret(input, seekNext(clickPosition));
  1150. } else
  1151. caret(input, lastPosition);
  1152. }
  1153. }, 0);
  1154. }).bind('dblclick.inputmask', function () {
  1155. var input = this;
  1156. setTimeout(function () {
  1157. caret(input, 0, seekNext(getLastValidPosition()));
  1158. }, 0);
  1159. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1160. ).bind('setvalue.inputmask', function () {
  1161. var input = this;
  1162. checkVal(input, true);
  1163. valueOnFocus = getBuffer().join('');
  1164. if (input._valueGet() == getBufferTemplate().join(''))
  1165. input._valueSet('');
  1166. }).bind('complete.inputmask', opts.oncomplete
  1167. ).bind('incomplete.inputmask', opts.onincomplete
  1168. ).bind('cleared.inputmask', opts.oncleared);
  1169. $el.bind("keydown.inputmask", keydownEvent
  1170. ).bind("keypress.inputmask", keypressEvent
  1171. ).bind("keyup.inputmask", keyupEvent);
  1172. // as the other inputevents aren't reliable for the moment we only base on the input event
  1173. // needs follow-up
  1174. if (android || androidfirefox || androidchrome || kindle) {
  1175. $el.attr("autocomplete", "off")
  1176. .attr("autocorrect", "off")
  1177. .attr("autocapitalize", "off")
  1178. .attr("spellcheck", false);
  1179. if (androidfirefox || kindle) {
  1180. $el.unbind("keydown.inputmask", keydownEvent
  1181. ).unbind("keypress.inputmask", keypressEvent
  1182. ).unbind("keyup.inputmask", keyupEvent);
  1183. if (PasteEventType == "input") {
  1184. $el.unbind(PasteEventType + ".inputmask");
  1185. }
  1186. $el.bind("input.inputmask", mobileInputEvent);
  1187. }
  1188. }
  1189. if (msie1x)
  1190. $el.bind("input.inputmask", pasteEvent);
  1191. //apply mask
  1192. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1193. checkVal(el, true, false, initialValue.split(''), true);
  1194. valueOnFocus = getBuffer().join('');
  1195. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1196. var activeElement;
  1197. try {
  1198. activeElement = document.activeElement;
  1199. } catch (e) {
  1200. }
  1201. if (activeElement === el) { //position the caret when in focus
  1202. $el.addClass('focus.inputmask');
  1203. caret(el, seekNext(getLastValidPosition()));
  1204. } else if (opts.clearMaskOnLostFocus) {
  1205. if (getBuffer().join('') == getBufferTemplate().join('')) {
  1206. el._valueSet('');
  1207. } else {
  1208. clearOptionalTail(el);
  1209. }
  1210. } else {
  1211. writeBuffer(el, getBuffer());
  1212. }
  1213. installEventRuler(el);
  1214. }
  1215. }
  1216. //action object
  1217. if (actionObj != undefined) {
  1218. switch (actionObj["action"]) {
  1219. case "isComplete":
  1220. $el = $(actionObj["el"]);
  1221. return isComplete(actionObj["buffer"]);
  1222. case "unmaskedvalue":
  1223. $el = actionObj["$input"];
  1224. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1225. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1226. case "mask":
  1227. mask(actionObj["el"]);
  1228. break;
  1229. case "format":
  1230. $el = $({});
  1231. $el.data('_inputmask', {
  1232. 'maskset': maskset,
  1233. 'opts': opts,
  1234. 'isRTL': opts.numericInput
  1235. });
  1236. if (opts.numericInput) {
  1237. opts.isNumeric = opts.numericInput;
  1238. isRTL = true;
  1239. }
  1240. var valueBuffer = actionObj["value"].split('');
  1241. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer, true);
  1242. return isRTL ? getBuffer().reverse().join('') : getBuffer().join('');
  1243. case "isValid":
  1244. $el = $({});
  1245. $el.data('_inputmask', {
  1246. 'maskset': maskset,
  1247. 'opts': opts,
  1248. 'isRTL': opts.numericInput
  1249. });
  1250. if (opts.numericInput) {
  1251. opts.isNumeric = opts.numericInput;
  1252. isRTL = true;
  1253. }
  1254. var valueBuffer = actionObj["value"].split('');
  1255. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1256. return isComplete(getBuffer());
  1257. }
  1258. }
  1259. };
  1260. function multiMaskScope(el, masksets, opts) {
  1261. function PatchValhookMulti(type) {
  1262. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskmultipatch != true) {
  1263. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  1264. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1265. elem.value = value;
  1266. return elem;
  1267. };
  1268. $.valHooks[type] = {
  1269. get: function (elem) {
  1270. var $elem = $(elem);
  1271. if ($elem.data('_inputmask-multi')) {
  1272. var data = $elem.data('_inputmask-multi');
  1273. return valueGet(data["elmasks"][data["activeMasksetIndex"]]);
  1274. } else return valueGet(elem);
  1275. },
  1276. set: function (elem, value) {
  1277. var $elem = $(elem);
  1278. var result = valueSet(elem, value);
  1279. if ($elem.data('_inputmask-multi')) $elem.triggerHandler('setvalue');
  1280. return result;
  1281. },
  1282. inputmaskmultipatch: true
  1283. };
  1284. }
  1285. }
  1286. function mcaret(input, begin, end) {
  1287. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  1288. if (typeof begin == 'number') {
  1289. begin = TranslatePosition(begin);
  1290. end = TranslatePosition(end);
  1291. end = (typeof end == 'number') ? end : begin;
  1292. //store caret for multi scope
  1293. if (npt != el) {
  1294. var data = $(npt).data('_inputmask') || {};
  1295. data["caret"] = { "begin": begin, "end": end };
  1296. $(npt).data('_inputmask', data);
  1297. }
  1298. if (!$(npt).is(':visible')) {
  1299. return;
  1300. }
  1301. npt.scrollLeft = npt.scrollWidth;
  1302. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  1303. if (npt.setSelectionRange) {
  1304. npt.selectionStart = begin;
  1305. npt.selectionEnd = end;
  1306. } else if (npt.createTextRange) {
  1307. range = npt.createTextRange();
  1308. range.collapse(true);
  1309. range.moveEnd('character', end);
  1310. range.moveStart('character', begin);
  1311. range.select();
  1312. }
  1313. } else {
  1314. if (!$(npt).is(':visible') && $(npt).data('_inputmask')["caret"] != undefined) {
  1315. var data = $(npt).data('_inputmask');
  1316. begin = data["caret"]["begin"];
  1317. end = data["caret"]["end"];
  1318. } else if (npt.setSelectionRange) {
  1319. begin = npt.selectionStart;
  1320. end = npt.selectionEnd;
  1321. } else if (document.selection && document.selection.createRange) {
  1322. range = document.selection.createRange();
  1323. begin = 0 - range.duplicate().moveStart('character', -100000);
  1324. end = begin + range.text.length;
  1325. }
  1326. begin = TranslatePosition(begin);
  1327. end = TranslatePosition(end);
  1328. return { "begin": begin, "end": end };
  1329. }
  1330. }
  1331. function TranslatePosition(pos) {
  1332. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  1333. var bffrLght = el.value.length;
  1334. pos = bffrLght - pos;
  1335. }
  1336. return pos;
  1337. }
  1338. function determineActiveMask(eventType, elmasks) {
  1339. if (eventType != "multiMaskScope") {
  1340. var lpc = -1, cp = -1, lvp = -1;;
  1341. $.each(elmasks, function (ndx, lmsk) {
  1342. var data = $(lmsk).data('_inputmask');
  1343. var maskset = data["maskset"];
  1344. var lastValidPosition = -1, validPositionCount = 0, caretPos = mcaret(lmsk).begin;
  1345. for (var posNdx in maskset["validPositions"]) {
  1346. var psNdx = parseInt(posNdx);
  1347. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  1348. validPositionCount++;
  1349. }
  1350. if (validPositionCount > lpc
  1351. || (validPositionCount == lpc && cp > caretPos && lvp > lastValidPosition)
  1352. || (validPositionCount == lpc && cp == caretPos && lvp < lastValidPosition)
  1353. ) {
  1354. //console.log("lvp " + lastValidPosition + " vpc " + validPositionCount + " caret " + caretPos + " ams " + ndx);
  1355. lpc = validPositionCount;
  1356. cp = caretPos;
  1357. activeMasksetIndex = ndx;
  1358. lvp = lastValidPosition;
  1359. }
  1360. });
  1361. if ($.isFunction(opts.determineActiveMasksetIndex)) activeMasksetIndex = opts.determineActiveMasksetIndex.call($el, eventType, elmasks);
  1362. var data = $el.data('_inputmask-multi') || { "activeMasksetIndex": 0, "elmasks": elmasks };
  1363. data["activeMasksetIndex"] = activeMasksetIndex;
  1364. $el.data('_inputmask-multi', data);
  1365. }
  1366. if (["focus"].indexOf(eventType) == -1 && el.value != elmasks[activeMasksetIndex]._valueGet()) {
  1367. var value = $(elmasks[activeMasksetIndex]).val() == "" ? elmasks[activeMasksetIndex]._valueGet() : $(elmasks[activeMasksetIndex]).val();
  1368. el.value = value;
  1369. }
  1370. if (["blur", "focus"].indexOf(eventType) == -1) {
  1371. if ($(elmasks[activeMasksetIndex]).hasClass("focus.inputmask")) {
  1372. var activeCaret = mcaret(elmasks[activeMasksetIndex]);
  1373. mcaret(el, activeCaret.begin, activeCaret.end);
  1374. }
  1375. }
  1376. }
  1377. opts.multi = true;
  1378. var $el = $(el), isRTL = el.dir == "rtl" || opts.numericInput;
  1379. var activeMasksetIndex = 0,
  1380. elmasks = $.map(masksets, function (msk, ndx) {
  1381. var elMaskStr = '<input type="text" ';
  1382. if ($el.attr("value")) elMaskStr += 'value="' + $el.attr("value") + '" ';
  1383. if ($el.attr("dir")) elMaskStr += 'dir="' + $el.attr("dir") + '" ';
  1384. elMaskStr += '/>';
  1385. var elmask = $(elMaskStr)[0];
  1386. maskScope($.extend(true, {}, msk), opts, { "action": "mask", "el": elmask });
  1387. return elmask;
  1388. });
  1389. $el.data('_inputmask-multi', { "activeMasksetIndex": 0, "elmasks": elmasks });
  1390. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1391. $el.css("text-align", "right");
  1392. el.dir = "ltr";
  1393. $el.removeAttr("dir");
  1394. if ($el.attr("value") != "") {
  1395. determineActiveMask("init", elmasks);
  1396. }
  1397. $el.bind("mouseenter blur focus mouseleave click dblclick keydown keypress keypress", function (e) {
  1398. var caretPos = mcaret(el), k, goDetermine = true;
  1399. if (e.type == "keydown") {
  1400. k = e.keyCode;
  1401. if (k == opts.keyCode.DOWN && activeMasksetIndex < elmasks.length - 1) {
  1402. activeMasksetIndex++;
  1403. determineActiveMask("multiMaskScope", elmasks);
  1404. return false;
  1405. } else if (k == opts.keyCode.UP && activeMasksetIndex > 0) {
  1406. activeMasksetIndex--;
  1407. determineActiveMask("multiMaskScope", elmasks);
  1408. return false;
  1409. } if (e.ctrlKey || e.shiftKey || e.altKey) {
  1410. return true;
  1411. }
  1412. } else if (e.type == "keypress" && (e.ctrlKey || e.shiftKey || e.altKey)) {
  1413. return true;
  1414. }
  1415. $.each(elmasks, function (ndx, lmnt) {
  1416. if (e.type == "keydown") {
  1417. k = e.keyCode;
  1418. if (k == opts.keyCode.BACKSPACE && lmnt._valueGet().length < caretPos.begin) {
  1419. return;
  1420. } else if (k == opts.keyCode.TAB) {
  1421. goDetermine = false;
  1422. } else if (k == opts.keyCode.RIGHT) {
  1423. mcaret(lmnt, caretPos.begin + 1, caretPos.end + 1);
  1424. goDetermine = false;
  1425. return;
  1426. } else if (k == opts.keyCode.LEFT) {
  1427. mcaret(lmnt, caretPos.begin - 1, caretPos.end - 1);
  1428. goDetermine = false;
  1429. return;
  1430. }
  1431. }
  1432. if (["click"].indexOf(e.type) != -1) {
  1433. mcaret(lmnt, TranslatePosition(caretPos.begin), TranslatePosition(caretPos.end));
  1434. if (caretPos.begin != caretPos.end) {
  1435. goDetermine = false;
  1436. return;
  1437. }
  1438. }
  1439. if (["keydown"].indexOf(e.type) != -1 && caretPos.begin != caretPos.end) {
  1440. mcaret(lmnt, caretPos.begin, caretPos.end);
  1441. }
  1442. $(lmnt).triggerHandler(e);
  1443. });
  1444. if (goDetermine) {
  1445. setTimeout(function () {
  1446. determineActiveMask(e.type, elmasks);
  1447. }, 0);
  1448. }
  1449. });
  1450. $el.bind(PasteEventType + " dragdrop drop setvalue", function (e) {
  1451. var caretPos = mcaret(el);
  1452. setTimeout(function () {
  1453. $.each(elmasks, function (ndx, lmnt) {
  1454. lmnt._valueSet(el.value);
  1455. $(lmnt).triggerHandler(e);
  1456. });
  1457. setTimeout(function () {
  1458. determineActiveMask(e.type, elmasks);
  1459. }, 0);
  1460. }, 0);
  1461. });
  1462. PatchValhookMulti(el.type);
  1463. };
  1464. $.inputmask = {
  1465. //options default
  1466. defaults: {
  1467. placeholder: "_",
  1468. optionalmarker: { start: "[", end: "]" },
  1469. quantifiermarker: { start: "{", end: "}" },
  1470. groupmarker: { start: "(", end: ")" },
  1471. alternatormarker: "|",
  1472. escapeChar: "\\",
  1473. mask: null,
  1474. oncomplete: $.noop, //executes when the mask is complete
  1475. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1476. oncleared: $.noop, //executes when the mask is cleared
  1477. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1478. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1479. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1480. clearMaskOnLostFocus: true,
  1481. insertMode: true, //insert the input or overwrite the input
  1482. clearIncomplete: false, //clear the incomplete input on blur
  1483. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1484. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  1485. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  1486. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1487. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1488. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1489. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1490. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1491. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1492. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1493. showTooltip: false, //show the activemask as tooltip
  1494. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1495. //numeric basic properties
  1496. isNumeric: false, //enable numeric features
  1497. radixPoint: "", //".", // | ","
  1498. skipRadixDance: false, //disable radixpoint caret positioning
  1499. rightAlignNumerics: true, //align numerics to the right
  1500. //numeric basic properties
  1501. definitions: {
  1502. '9': {
  1503. validator: "[0-9]",
  1504. cardinality: 1,
  1505. definitionSymbol: "*"
  1506. },
  1507. 'a': {
  1508. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1509. cardinality: 1,
  1510. definitionSymbol: "*"
  1511. },
  1512. '*': {
  1513. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1514. cardinality: 1
  1515. }
  1516. },
  1517. keyCode: {
  1518. 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,
  1519. 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
  1520. },
  1521. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1522. 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],
  1523. isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false
  1524. //multi-masks
  1525. multi: false, //do not alter - internal use
  1526. nojumps: false, //do not jump over fixed parts in the mask
  1527. nojumpsThreshold: 0, //start nojumps as of
  1528. determineActiveMasksetIndex: undefined //override determineActiveMasksetIndex - args => eventType, elmasks - return int
  1529. },
  1530. masksCache: {},
  1531. escapeRegex: function (str) {
  1532. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1533. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1534. },
  1535. format: function (value, options) {
  1536. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1537. resolveAlias(opts.alias, options, opts);
  1538. return maskScope(generateMaskSet(opts), opts, { "action": "format", "value": value });
  1539. },
  1540. isValid: function (value, options) {
  1541. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1542. resolveAlias(opts.alias, options, opts);
  1543. return maskScope(generateMaskSet(opts), opts, { "action": "isValid", "value": value });
  1544. }
  1545. };
  1546. $.fn.inputmask = function (fn, options) {
  1547. function importAttributeOptions(npt, opts) {
  1548. var $npt = $(npt);
  1549. for (var option in opts) {
  1550. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  1551. if (optionData != undefined)
  1552. opts[option] = optionData;
  1553. }
  1554. return opts;
  1555. }
  1556. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1557. maskset;
  1558. if (typeof fn === "string") {
  1559. switch (fn) {
  1560. case "mask":
  1561. //resolve possible aliases given by options
  1562. resolveAlias(opts.alias, options, opts);
  1563. maskset = generateMaskSet(opts);
  1564. if (maskset.length == 0) { return this; }
  1565. return this.each(function () {
  1566. if ($.isArray(maskset)) {
  1567. multiMaskScope(this, maskset, importAttributeOptions(this, opts));
  1568. } else
  1569. maskScope($.extend(true, {}, maskset), importAttributeOptions(this, opts), { "action": "mask", "el": this });
  1570. });
  1571. case "unmaskedvalue":
  1572. var $input = $(this), input = this;
  1573. if ($input.data('_inputmask')) {
  1574. maskset = $input.data('_inputmask')['maskset'];
  1575. opts = $input.data('_inputmask')['opts'];
  1576. return maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input });
  1577. } else return $input.val();
  1578. case "remove":
  1579. return this.each(function () {
  1580. var $input = $(this), input = this;
  1581. if ($input.data('_inputmask')) {
  1582. maskset = $input.data('_inputmask')['maskset'];
  1583. opts = $input.data('_inputmask')['opts'];
  1584. //writeout the unmaskedvalue
  1585. input._valueSet(maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true }));
  1586. //clear data
  1587. $input.removeData('_inputmask');
  1588. //unbind all events
  1589. $input.unbind(".inputmask");
  1590. $input.removeClass('focus.inputmask');
  1591. //restore the value property
  1592. var valueProperty;
  1593. if (Object.getOwnPropertyDescriptor)
  1594. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  1595. if (valueProperty && valueProperty.get) {
  1596. if (input._valueGet) {
  1597. Object.defineProperty(input, "value", {
  1598. get: input._valueGet,
  1599. set: input._valueSet
  1600. });
  1601. }
  1602. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  1603. if (input._valueGet) {
  1604. input.__defineGetter__("value", input._valueGet);
  1605. input.__defineSetter__("value", input._valueSet);
  1606. }
  1607. }
  1608. try { //try catch needed for IE7 as it does not supports deleting fns
  1609. delete input._valueGet;
  1610. delete input._valueSet;
  1611. } catch (e) {
  1612. input._valueGet = undefined;
  1613. input._valueSet = undefined;
  1614. }
  1615. }
  1616. });
  1617. break;
  1618. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1619. if (this.data('_inputmask')) {
  1620. maskset = this.data('_inputmask')['maskset'];
  1621. return maskset['_buffer'].join('');
  1622. }
  1623. else return "";
  1624. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1625. return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
  1626. case "isComplete":
  1627. if (this.data('_inputmask')) {
  1628. maskset = this.data('_inputmask')['maskset'];
  1629. opts = this.data('_inputmask')['opts'];
  1630. return maskScope(maskset, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
  1631. } else return true;
  1632. case "getmetadata": //return mask metadata if exists
  1633. if (this.data('_inputmask')) {
  1634. maskset = this.data('_inputmask')['maskset'];
  1635. return maskset['metadata'];
  1636. }
  1637. else return undefined;
  1638. default:
  1639. //check if the fn is an alias
  1640. if (!resolveAlias(fn, options, opts)) {
  1641. //maybe fn is a mask so we try
  1642. //set mask
  1643. opts.mask = fn;
  1644. }
  1645. maskset = generateMaskSet(opts);
  1646. if (maskset == undefined) { return this; }
  1647. return this.each(function () {
  1648. if ($.isArray(maskset)) {
  1649. multiMaskScope(this, maskset, importAttributeOptions(this, opts));
  1650. } else
  1651. maskScope($.extend(true, {}, maskset), importAttributeOptions(this, opts), { "action": "mask", "el": this });
  1652. });
  1653. break;
  1654. }
  1655. } else if (typeof fn == "object") {
  1656. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1657. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1658. maskset = generateMaskSet(opts);
  1659. if (maskset == undefined) { return this; }
  1660. return this.each(function () {
  1661. if ($.isArray(maskset)) {
  1662. multiMaskScope(this, maskset, importAttributeOptions(this, opts));
  1663. } else
  1664. maskScope($.extend(true, {}, maskset), importAttributeOptions(this, opts), { "action": "mask", "el": this });
  1665. });
  1666. } else if (fn == undefined) {
  1667. //look for data-inputmask atribute - the attribute should only contain optipns
  1668. return this.each(function () {
  1669. var attrOptions = $(this).attr("data-inputmask");
  1670. if (attrOptions && attrOptions != "") {
  1671. try {
  1672. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1673. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1674. $.extend(true, dataoptions, options);
  1675. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1676. resolveAlias(opts.alias, dataoptions, opts);
  1677. opts.alias = undefined;
  1678. $(this).inputmask(opts);
  1679. } catch (ex) { } //need a more relax parseJSON
  1680. }
  1681. });
  1682. }
  1683. };
  1684. }
  1685. })(jQuery);