jquery.inputmask.js 96 KB

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