jquery.inputmask.js 96 KB

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