jquery.inputmask.js 94 KB

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