jquery.inputmask.js 103 KB

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