jquery.inputmask.js 94 KB

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