jquery.inputmask.js 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  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(baseOnInput, minimalPos) {
  300. minimalPos = minimalPos || 0;
  301. var maskTemplate = [], ndxIntlzr, pos = 0, test;
  302. do {
  303. if (baseOnInput === true && getActiveMaskSet()['validPositions'][pos]) {
  304. var validPos = getActiveMaskSet()['validPositions'][pos];
  305. test = validPos["match"];
  306. ndxIntlzr = validPos["locator"].slice();
  307. maskTemplate.push(test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  308. } else {
  309. var testPos = getActiveTests(pos, false, ndxIntlzr, pos - 1);
  310. testPos = testPos[opts.greedy || minimalPos > pos ? 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. var psNdx = parseInt(posNdx);
  328. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  329. }
  330. return lastValidPosition;
  331. }
  332. function setLastValidPosition(pos, maskset) {
  333. maskset = maskset || getActiveMaskSet();
  334. for (var posNdx in maskset["validPositions"]) {
  335. if (posNdx > pos) maskset["validPositions"][posNdx] = undefined;
  336. }
  337. }
  338. function getActiveTest(pos) {
  339. if (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)) && testPos <= pos; 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. } else if (testPos > pos) {
  396. break;
  397. }
  398. }
  399. }
  400. }
  401. if (disableCache !== true && getActiveMaskSet()['tests'][pos] && !getActiveMaskSet()['validPositions'][pos]) {
  402. return getActiveMaskSet()['tests'][pos];
  403. }
  404. if (ndxIntlzr == undefined) {
  405. var previousPos = pos - 1, test;
  406. while ((test = getActiveMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  407. previousPos--;
  408. }
  409. if (test != undefined && previousPos > -1) {
  410. testPos = previousPos;
  411. ndxInitializer = test["locator"].slice();
  412. } else {
  413. previousPos = pos - 1;
  414. while ((test = getActiveMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  415. previousPos--;
  416. }
  417. if (test != undefined && previousPos > -1) {
  418. testPos = previousPos;
  419. ndxInitializer = test[0]["locator"].slice();
  420. }
  421. }
  422. }
  423. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  424. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  425. if ((match && testPos == pos) || testPos > pos) {
  426. break;
  427. }
  428. }
  429. if (matches.length == 0)
  430. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  431. getActiveMaskSet()['tests'][pos] = matches;
  432. return matches;
  433. }
  434. function getActiveBufferTemplate() {
  435. if (getActiveMaskSet()['_buffer'] == undefined) {
  436. //generate template
  437. var maskTemplate = getMaskTemplate(false, 1);
  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]);
  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);
  527. setLastValidPosition(lowestPos);
  528. }
  529. return rslt;
  530. }
  531. }
  532. });
  533. }
  534. return results;
  535. }
  536. if (strict) {
  537. var result = _isValid(pos, c, strict); //only check validity in current mask when validating strict
  538. if (result === true) {
  539. result = { "pos": pos }; //always take a possible corrected maskposition into account
  540. }
  541. return result;
  542. }
  543. var results = [], result = false, currentActiveMasksetIndex = activeMasksetIndex,
  544. actualBuffer = getActiveBuffer().slice(), actualLVP = getLastValidPosition(),
  545. actualPrevious = seekPrevious(pos),
  546. maskForwards = [];
  547. $.each(masksets, function (index, value) {
  548. if (typeof (value) == "object") {
  549. activeMasksetIndex = index;
  550. var maskPos = pos;
  551. var lvp = getLastValidPosition(),
  552. rsltValid;
  553. if (lvp == actualLVP) {
  554. if ((maskPos - actualLVP) > 1) {
  555. for (var i = lvp == -1 ? 0 : lvp; i < maskPos; i++) {
  556. rsltValid = _isValid(i, actualBuffer[i], true);
  557. if (rsltValid === false) {
  558. break;
  559. } else {
  560. setBufferElement(getActiveBuffer(), i, actualBuffer[i]);
  561. if (rsltValid === true) {
  562. rsltValid = { "pos": i }; //always take a possible corrected maskposition into account
  563. }
  564. }
  565. }
  566. }
  567. //does the input match on a further position?
  568. if (!isMask(maskPos) && !_isValid(maskPos, c, strict)) {
  569. var maxForward = seekNext(maskPos) - maskPos;
  570. for (var fw = 0; fw < maxForward; fw++) {
  571. if (_isValid(++maskPos, c, strict) !== false)
  572. break;
  573. }
  574. maskForwards.push(activeMasksetIndex);
  575. //console.log('maskforward ' + activeMasksetIndex + " pos " + pos + " maskPos " + maskPos);
  576. }
  577. }
  578. if (getLastValidPosition() >= actualLVP || activeMasksetIndex == currentActiveMasksetIndex) {
  579. if (maskPos >= 0 && maskPos < getMaskLength()) {
  580. result = _isValid(maskPos, c, strict);
  581. if (result !== false) {
  582. if (result === true) {
  583. result = { "pos": maskPos }; //always take a possible corrected maskposition into account
  584. }
  585. }
  586. results.push({ "activeMasksetIndex": index, "result": result });
  587. }
  588. }
  589. }
  590. });
  591. var postResults = PostProcessResults(maskForwards, results); //return results of the multiple mask validations
  592. activeMasksetIndex = currentActiveMasksetIndex; //reset activeMasksetIndex
  593. return postResults;
  594. }
  595. function determineActiveMasksetIndex() {
  596. var currentMasksetIndex = activeMasksetIndex,
  597. highestValid = { "activeMasksetIndex": 0, "lastValidPosition": -1, "next": -1 };
  598. $.each(masksets, function (index, value) {
  599. if (typeof (value) == "object") {
  600. activeMasksetIndex = index;
  601. if (getLastValidPosition() > highestValid['lastValidPosition']) {
  602. highestValid["activeMasksetIndex"] = index;
  603. highestValid["lastValidPosition"] = getLastValidPosition();
  604. highestValid["next"] = seekNext(getLastValidPosition());
  605. } else if (getLastValidPosition() == highestValid['lastValidPosition'] &&
  606. (highestValid['next'] == -1 || highestValid['next'] > seekNext(getLastValidPosition()))) {
  607. highestValid["activeMasksetIndex"] = index;
  608. highestValid["lastValidPosition"] = getLastValidPosition();
  609. highestValid["next"] = seekNext(getLastValidPosition());
  610. }
  611. }
  612. });
  613. activeMasksetIndex = highestValid["lastValidPosition"] != -1 && getLastValidPosition(masksets[currentMasksetIndex]) == highestValid["lastValidPosition"] ? currentMasksetIndex : highestValid["activeMasksetIndex"];
  614. if (currentMasksetIndex != activeMasksetIndex) {
  615. clearBuffer(getActiveBuffer(), seekNext(highestValid["lastValidPosition"]), getMaskLength());
  616. getActiveMaskSet()["writeOutBuffer"] = true;
  617. }
  618. $el.data('_inputmask')['activeMasksetIndex'] = activeMasksetIndex; //store the activeMasksetIndex
  619. }
  620. function isMask(pos) {
  621. var test = getActiveTest(pos);
  622. return test.fn != null ? test.fn : false;
  623. }
  624. function getMaskLength() {
  625. var maxLength = $el.prop('maxLength'), maskLength;
  626. if (!getActiveMaskSet()['greedy']) {
  627. var lvp = getLastValidPosition() + 1,
  628. test = getActiveTest(lvp);
  629. while (test.fn != null && test.def != "") {
  630. var tests = getActiveTests(++lvp);
  631. test = tests[tests.length - 1];
  632. }
  633. maskLength = getMaskTemplate(false, lvp)["mask"].length;
  634. } else
  635. maskLength = getActiveBuffer().length;
  636. return maskLength < maxLength && maxLength > -1 /* FF sets no defined max length to -1 */ ? maskLength : maxLength;
  637. }
  638. //pos: from position
  639. function seekNext(pos) {
  640. var maskL = getMaskLength();
  641. if (pos >= maskL) return maskL;
  642. var position = pos;
  643. while (++position < maskL && !isMask(position)) {
  644. }
  645. return position;
  646. }
  647. //pos: from position
  648. function seekPrevious(pos) {
  649. var position = pos;
  650. if (position <= 0) return 0;
  651. while (--position > 0 && !isMask(position)) {
  652. }
  653. ;
  654. return position;
  655. }
  656. function setBufferElement(buffer, position, element) {
  657. position = prepareBuffer(buffer, position);
  658. var test = getActiveTest(position);
  659. var elem = element;
  660. if (elem != undefined && test != undefined) {
  661. switch (test.casing) {
  662. case "upper":
  663. elem = element.toUpperCase();
  664. break;
  665. case "lower":
  666. elem = element.toLowerCase();
  667. break;
  668. }
  669. }
  670. buffer[position] = elem;
  671. }
  672. function getBufferElement(buffer, position) {
  673. position = prepareBuffer(buffer, position);
  674. return buffer[position];
  675. }
  676. //needed to handle the non-greedy mask repetitions
  677. function prepareBuffer(buffer, position) { //TODO DROP BUFFER PASSING + optimize me
  678. if (buffer.length <= position) {
  679. var trbuffer = getMaskTemplate(true, position).mask;
  680. buffer.length = trbuffer.length;
  681. for (var i = 0, bl = buffer.length; i < bl; i++) {
  682. if (buffer[i] == undefined)
  683. buffer[i] = trbuffer[i];
  684. }
  685. buffer[position] = getPlaceholder(position);
  686. }
  687. return position;
  688. }
  689. function writeBuffer(input, buffer, caretPos) {
  690. input._valueSet(buffer.join(''));
  691. if (caretPos != undefined) {
  692. caret(input, caretPos);
  693. }
  694. }
  695. function clearBuffer(buffer, start, end, stripNomasks) {
  696. for (var i = start, maskL = getMaskLength() ; i < end && i < maskL; i++) {
  697. if (stripNomasks === true) {
  698. if (!isMask(i))
  699. setBufferElement(buffer, i, "");
  700. } else
  701. setBufferElement(buffer, i, getPlaceholder(i));
  702. }
  703. }
  704. function setPlaceholder(pos) {
  705. setBufferElement(getActiveBuffer(), pos, getPlaceholder(pos));
  706. }
  707. function getPlaceholder(pos) {
  708. var test = getActiveTest(pos);
  709. return test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length);
  710. }
  711. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  712. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  713. $.each(masksets, function (ndx, ms) {
  714. if (typeof (ms) == "object") {
  715. ms["buffer"] = undefined;
  716. ms["_buffer"] = undefined;
  717. ms["validPositions"] = {};
  718. ms["p"] = -1;
  719. }
  720. });
  721. if (strict !== true) activeMasksetIndex = 0;
  722. if (writeOut) input._valueSet(""); //initial clear
  723. var ml = getMaskLength();
  724. $.each(inputValue, function (ndx, charCode) {
  725. if (intelliCheck === true) {
  726. var p = getActiveMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p),
  727. pos = lvp == -1 ? ndx : seekNext(lvp);
  728. if ($.inArray(charCode, getActiveBufferTemplate().slice(lvp + 1, pos)) == -1) {
  729. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  730. }
  731. } else {
  732. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  733. strict = strict || (ndx > 0 && ndx > getActiveMaskSet()["p"]);
  734. }
  735. });
  736. }
  737. function escapeRegex(str) {
  738. return $.inputmask.escapeRegex.call(this, str);
  739. }
  740. function truncateInput(inputValue) {
  741. return inputValue.replace(new RegExp("(" + escapeRegex(getActiveBufferTemplate().join('')) + ")*$"), "");
  742. }
  743. function clearOptionalTail(input) {
  744. var buffer = getActiveBuffer(), tmpBuffer = buffer.slice(), testPos, pos;
  745. for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  746. if (getActiveTest(pos).optionality) {
  747. if (!isMask(pos) || !isValid(pos, buffer[pos], true))
  748. tmpBuffer.pop();
  749. else break;
  750. } else break;
  751. }
  752. writeBuffer(input, tmpBuffer);
  753. }
  754. function unmaskedvalue($input, skipDatepickerCheck) {
  755. if ($input.data('_inputmask') && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  756. var umValue = $.map(getActiveBuffer(), function (element, index) {
  757. return isMask(index) && isValid(index, element, true) ? element : null;
  758. });
  759. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  760. return $.isFunction(opts.onUnMask) ? opts.onUnMask.call($input, getActiveBuffer().join(''), unmaskedValue, opts) : unmaskedValue;
  761. } else {
  762. return $input[0]._valueGet();
  763. }
  764. }
  765. function TranslatePosition(pos) {
  766. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  767. var bffrLght = getActiveBuffer().length;
  768. pos = bffrLght - pos;
  769. }
  770. return pos;
  771. }
  772. function caret(input, begin, end) {
  773. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  774. if (typeof begin == 'number') {
  775. begin = TranslatePosition(begin);
  776. end = TranslatePosition(end);
  777. if (!$(npt).is(':visible')) {
  778. return;
  779. }
  780. end = (typeof end == 'number') ? end : begin;
  781. npt.scrollLeft = npt.scrollWidth;
  782. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  783. if (npt.setSelectionRange) {
  784. npt.selectionStart = begin;
  785. npt.selectionEnd = end;
  786. } else if (npt.createTextRange) {
  787. range = npt.createTextRange();
  788. range.collapse(true);
  789. range.moveEnd('character', end);
  790. range.moveStart('character', begin);
  791. range.select();
  792. }
  793. } else {
  794. if (!$(input).is(':visible')) {
  795. return { "begin": 0, "end": 0 };
  796. }
  797. if (npt.setSelectionRange) {
  798. begin = npt.selectionStart;
  799. end = npt.selectionEnd;
  800. } else if (document.selection && document.selection.createRange) {
  801. range = document.selection.createRange();
  802. begin = 0 - range.duplicate().moveStart('character', -100000);
  803. end = begin + range.text.length;
  804. }
  805. begin = TranslatePosition(begin);
  806. end = TranslatePosition(end);
  807. return { "begin": begin, "end": end };
  808. }
  809. }
  810. function isComplete(buffer) { //return true / false / undefined (repeat *)
  811. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  812. if (opts.repeat == "*") return undefined;
  813. var complete = false, highestValidPosition = 0, currentActiveMasksetIndex = activeMasksetIndex;
  814. $.each(masksets, function (ndx, ms) {
  815. if (typeof (ms) == "object") {
  816. activeMasksetIndex = ndx;
  817. var aml = seekPrevious(getMaskLength());
  818. if (getLastValidPosition() >= highestValidPosition && getLastValidPosition() == aml) {
  819. var msComplete = true;
  820. for (var i = 0; i <= aml; i++) {
  821. var mask = isMask(i);
  822. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  823. msComplete = false;
  824. break;
  825. }
  826. }
  827. complete = complete || msComplete;
  828. if (complete) //break loop
  829. return false;
  830. }
  831. highestValidPosition = getLastValidPosition();
  832. }
  833. });
  834. activeMasksetIndex = currentActiveMasksetIndex; //reset activeMaskset
  835. return complete;
  836. }
  837. function isSelection(begin, end) {
  838. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  839. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  840. }
  841. function installEventRuler(npt) {
  842. var events = $._data(npt).events;
  843. $.each(events, function (eventType, eventHandlers) {
  844. $.each(eventHandlers, function (ndx, eventHandler) {
  845. if (eventHandler.namespace == "inputmask") {
  846. if (eventHandler.type != "setvalue") {
  847. var handler = eventHandler.handler;
  848. eventHandler.handler = function (e) {
  849. if (this.readOnly || this.disabled)
  850. e.preventDefault;
  851. else
  852. return handler.apply(this, arguments);
  853. };
  854. }
  855. }
  856. });
  857. });
  858. }
  859. function patchValueProperty(npt) {
  860. function PatchValhook(type) {
  861. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  862. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  863. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  864. elem.value = value;
  865. return elem;
  866. };
  867. $.valHooks[type] = {
  868. get: function (elem) {
  869. var $elem = $(elem);
  870. if ($elem.data('_inputmask')) {
  871. if ($elem.data('_inputmask')['opts'].autoUnmask)
  872. return $elem.inputmask('unmaskedvalue');
  873. else {
  874. var result = valueGet(elem),
  875. inputData = $elem.data('_inputmask'), masksets = inputData['masksets'],
  876. activeMasksetIndex = inputData['activeMasksetIndex'],
  877. bufferTemplate = masksets[activeMasksetIndex]['_buffer'];
  878. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  879. return result != bufferTemplate ? result : '';
  880. }
  881. } else return valueGet(elem);
  882. },
  883. set: function (elem, value) {
  884. var $elem = $(elem);
  885. var result = valueSet(elem, value);
  886. if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
  887. return result;
  888. },
  889. inputmaskpatch: true
  890. };
  891. }
  892. }
  893. var valueProperty;
  894. if (Object.getOwnPropertyDescriptor)
  895. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  896. if (valueProperty && valueProperty.get) {
  897. if (!npt._valueGet) {
  898. var valueGet = valueProperty.get;
  899. var valueSet = valueProperty.set;
  900. npt._valueGet = function () {
  901. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  902. };
  903. npt._valueSet = function (value) {
  904. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  905. };
  906. Object.defineProperty(npt, "value", {
  907. get: function () {
  908. var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'],
  909. activeMasksetIndex = inputData['activeMasksetIndex'];
  910. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : '';
  911. },
  912. set: function (value) {
  913. valueSet.call(this, value);
  914. $(this).triggerHandler('setvalue.inputmask');
  915. }
  916. });
  917. }
  918. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  919. if (!npt._valueGet) {
  920. var valueGet = npt.__lookupGetter__("value");
  921. var valueSet = npt.__lookupSetter__("value");
  922. npt._valueGet = function () {
  923. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  924. };
  925. npt._valueSet = function (value) {
  926. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  927. };
  928. npt.__defineGetter__("value", function () {
  929. var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'],
  930. activeMasksetIndex = inputData['activeMasksetIndex'];
  931. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : '';
  932. });
  933. npt.__defineSetter__("value", function (value) {
  934. valueSet.call(this, value);
  935. $(this).triggerHandler('setvalue.inputmask');
  936. });
  937. }
  938. } else {
  939. if (!npt._valueGet) {
  940. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  941. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  942. }
  943. PatchValhook(npt.type);
  944. }
  945. }
  946. //shift chars to left from start to end and put c at end position if defined
  947. function shiftL(start, end, c, maskJumps) {
  948. var buffer = getActiveBuffer();
  949. if (maskJumps !== false) //jumping over nonmask position
  950. while (!isMask(start) && start - 1 >= 0) start--;
  951. for (var i = start; i < end && i < getMaskLength() ; i++) {
  952. if (isMask(i)) {
  953. setPlaceholder(i);
  954. var j = seekNext(i);
  955. var p = getBufferElement(buffer, j);
  956. if (p != getPlaceholder(j)) {
  957. if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTest(i).def == getActiveTest(j).def) {
  958. setBufferElement(buffer, i, p);
  959. if (j < end) {
  960. setPlaceholder(j); //cleanup next position
  961. }
  962. } else {
  963. if (isMask(i))
  964. break;
  965. }
  966. }
  967. } else {
  968. setPlaceholder(i);
  969. }
  970. }
  971. if (c != undefined)
  972. setBufferElement(buffer, seekPrevious(end), c);
  973. if (getActiveMaskSet()["greedy"] == false) {
  974. var trbuffer = truncateInput(buffer.join('')).split('');
  975. buffer.length = trbuffer.length;
  976. for (var i = 0, bl = buffer.length; i < bl; i++) {
  977. buffer[i] = trbuffer[i];
  978. }
  979. if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice();
  980. }
  981. return start; //return the used start position
  982. }
  983. function shiftR(start, end, c) {
  984. var buffer = getActiveBuffer();
  985. if (getBufferElement(buffer, start) != getPlaceholder(start)) {
  986. for (var i = seekPrevious(end) ; i > start && i >= 0; i--) {
  987. if (isMask(i)) {
  988. var j = seekPrevious(i);
  989. var t = getBufferElement(buffer, j);
  990. if (t != getPlaceholder(j)) {
  991. if (isValid(i, t, true) !== false && getActiveTest(i).def == getActiveTest(j).def) {
  992. setBufferElement(buffer, i, t);
  993. setPlaceholder(j);
  994. } //else break;
  995. }
  996. } else
  997. setPlaceholder(i);
  998. }
  999. }
  1000. if (c != undefined && getBufferElement(buffer, start) == getPlaceholder(start))
  1001. setBufferElement(buffer, start, c);
  1002. var lengthBefore = buffer.length;
  1003. if (getActiveMaskSet()["greedy"] == false) {
  1004. var trbuffer = truncateInput(buffer.join('')).split('');
  1005. buffer.length = trbuffer.length;
  1006. for (var i = 0, bl = buffer.length; i < bl; i++) {
  1007. buffer[i] = trbuffer[i];
  1008. }
  1009. if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice();
  1010. }
  1011. return end - (lengthBefore - buffer.length); //return new start position
  1012. }
  1013. function HandleRemove(input, k, pos) {
  1014. if (opts.numericInput || isRTL) {
  1015. switch (k) {
  1016. case opts.keyCode.BACKSPACE:
  1017. k = opts.keyCode.DELETE;
  1018. break;
  1019. case opts.keyCode.DELETE:
  1020. k = opts.keyCode.BACKSPACE;
  1021. break;
  1022. }
  1023. if (isRTL) {
  1024. var pend = pos.end;
  1025. pos.end = pos.begin;
  1026. pos.begin = pend;
  1027. }
  1028. }
  1029. var isSelection = true;
  1030. if (pos.begin == pos.end) {
  1031. var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
  1032. if (opts.isNumeric && opts.radixPoint != "" && getActiveBuffer()[posBegin] == opts.radixPoint) {
  1033. pos.begin = (getActiveBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
  1034. pos.end = pos.begin;
  1035. }
  1036. isSelection = false;
  1037. if (k == opts.keyCode.BACKSPACE)
  1038. pos.begin--;
  1039. else if (k == opts.keyCode.DELETE)
  1040. pos.end++;
  1041. } else if (pos.end - pos.begin == 1 && !opts.insertMode) {
  1042. isSelection = false;
  1043. if (k == opts.keyCode.BACKSPACE)
  1044. pos.begin--;
  1045. }
  1046. clearBuffer(getActiveBuffer(), pos.begin, pos.end);
  1047. var ml = getMaskLength();
  1048. if (opts.greedy == false && (isNaN(opts.repeat) || opts.repeat > 0)) {
  1049. shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
  1050. } else {
  1051. var newpos = pos.begin;
  1052. for (var i = pos.begin; i < pos.end; i++) { //seeknext to skip placeholders at start in selection
  1053. if (isMask(i) || !isSelection)
  1054. newpos = shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
  1055. }
  1056. if (!isSelection) pos.begin = newpos;
  1057. }
  1058. var firstMaskPos = seekNext(-1);
  1059. clearBuffer(getActiveBuffer(), pos.begin, pos.end, true);
  1060. checkVal(input, false, false, getActiveBuffer());
  1061. if (getLastValidPosition() < firstMaskPos) {
  1062. getActiveMaskSet()["p"] = firstMaskPos;
  1063. } else {
  1064. getActiveMaskSet()["p"] = pos.begin;
  1065. }
  1066. }
  1067. function keydownEvent(e) {
  1068. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1069. skipKeyPressEvent = false;
  1070. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1071. //backspace, delete, and escape get special treatment
  1072. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  1073. e.preventDefault(); //stop default action but allow propagation
  1074. if (k == 88) valueOnFocus = getActiveBuffer().join('');
  1075. HandleRemove(input, k, pos);
  1076. determineActiveMasksetIndex();
  1077. writeBuffer(input, getActiveBuffer(), getActiveMaskSet()["p"]);
  1078. if (input._valueGet() == getActiveBufferTemplate().join(''))
  1079. $input.trigger('cleared');
  1080. if (opts.showTooltip) { //update tooltip
  1081. $input.prop("title", getActiveMaskSet()["mask"]);
  1082. }
  1083. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1084. setTimeout(function () {
  1085. var caretPos = seekNext(getLastValidPosition());
  1086. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1087. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1088. }, 0);
  1089. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  1090. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1091. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  1092. checkVal(input, true, false, valueOnFocus.split(''));
  1093. $input.click();
  1094. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1095. opts.insertMode = !opts.insertMode;
  1096. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1097. } else if (opts.insertMode == false && !e.shiftKey) {
  1098. if (k == opts.keyCode.RIGHT) {
  1099. setTimeout(function () {
  1100. var caretPos = caret(input);
  1101. caret(input, caretPos.begin);
  1102. }, 0);
  1103. } else if (k == opts.keyCode.LEFT) {
  1104. setTimeout(function () {
  1105. var caretPos = caret(input);
  1106. caret(input, caretPos.begin - 1);
  1107. }, 0);
  1108. }
  1109. }
  1110. var currentCaretPos = caret(input);
  1111. if (opts.onKeyDown.call(this, e, getActiveBuffer(), opts) === true) //extra stuff to execute on keydown
  1112. caret(input, currentCaretPos.begin, currentCaretPos.end);
  1113. ignorable = $.inArray(k, opts.ignorables) != -1;
  1114. }
  1115. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  1116. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1117. if (k == undefined && skipKeyPressEvent) return false;
  1118. skipKeyPressEvent = true;
  1119. var input = this, $input = $(input);
  1120. e = e || window.event;
  1121. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  1122. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1123. return true;
  1124. } else {
  1125. if (k) {
  1126. //special treat the decimal separator
  1127. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1128. var pos, results, result, c = String.fromCharCode(k);
  1129. if (checkval) {
  1130. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  1131. pos = { begin: pcaret, end: pcaret };
  1132. } else {
  1133. pos = caret(input);
  1134. }
  1135. //should we clear a possible selection??
  1136. var isSlctn = isSelection(pos.begin, pos.end),
  1137. initialIndex = activeMasksetIndex;
  1138. if (isSlctn) {
  1139. $.each(masksets, function (ndx, lmnt) { //init undobuffer for recovery when not valid
  1140. if (typeof (lmnt) == "object") {
  1141. activeMasksetIndex = ndx;
  1142. getActiveMaskSet()["undoBuffer"] = getActiveBuffer().join('');
  1143. }
  1144. });
  1145. activeMasksetIndex = initialIndex; //restore index
  1146. HandleRemove(input, opts.keyCode.DELETE, pos);
  1147. if (!opts.insertMode) { //preserve some space
  1148. $.each(masksets, function (ndx, lmnt) {
  1149. if (typeof (lmnt) == "object") {
  1150. activeMasksetIndex = ndx;
  1151. shiftR(pos.begin, getMaskLength());
  1152. }
  1153. });
  1154. }
  1155. activeMasksetIndex = initialIndex; //restore index
  1156. }
  1157. var radixPosition = getActiveBuffer().join('').indexOf(opts.radixPoint);
  1158. if (opts.isNumeric && checkval !== true && radixPosition != -1) {
  1159. if (opts.greedy && pos.begin <= radixPosition) {
  1160. pos.begin = seekPrevious(pos.begin);
  1161. pos.end = pos.begin;
  1162. } else if (c == opts.radixPoint) {
  1163. pos.begin = radixPosition;
  1164. pos.end = pos.begin;
  1165. }
  1166. }
  1167. var p = pos.begin;
  1168. results = isValid(p, c, strict);
  1169. if (strict === true) results = [{ "activeMasksetIndex": activeMasksetIndex, "result": results }];
  1170. var minimalForwardPosition = -1;
  1171. $.each(results, function (index, result) {
  1172. activeMasksetIndex = result["activeMasksetIndex"];
  1173. getActiveMaskSet()["writeOutBuffer"] = true;
  1174. var np = result["result"];
  1175. if (np !== false) {
  1176. var refresh = false, buffer = getActiveBuffer();
  1177. if (np !== true) {
  1178. refresh = np["refresh"]; //only rewrite buffer from isValid
  1179. p = np.pos != undefined ? np.pos : p; //set new position from isValid
  1180. c = np.c != undefined ? np.c : c; //set new char from isValid
  1181. }
  1182. if (refresh !== true) {
  1183. if (opts.insertMode == true) {
  1184. var freePos = p;
  1185. if (getBufferElement(buffer, p) != getPlaceholder(p)) {
  1186. while (getActiveMaskSet()["validPositions"][freePos]) {
  1187. freePos = seekNext(freePos);
  1188. }
  1189. }
  1190. if (freePos < getMaskLength()) {
  1191. shiftR(p, getMaskLength(), c);
  1192. } else getActiveMaskSet()["writeOutBuffer"] = false;
  1193. } else setBufferElement(buffer, p, c);
  1194. if (minimalForwardPosition == -1 || minimalForwardPosition > seekNext(p)) {
  1195. minimalForwardPosition = seekNext(p);
  1196. }
  1197. } else if (!strict) {
  1198. var nextPos = p < getMaskLength() ? p + 1 : p;
  1199. if (minimalForwardPosition == -1 || minimalForwardPosition > nextPos) {
  1200. minimalForwardPosition = nextPos;
  1201. }
  1202. }
  1203. if (minimalForwardPosition > getActiveMaskSet()["p"])
  1204. getActiveMaskSet()["p"] = minimalForwardPosition; //needed for checkval strict
  1205. }
  1206. });
  1207. if (strict !== true) {
  1208. activeMasksetIndex = initialIndex;
  1209. determineActiveMasksetIndex();
  1210. }
  1211. if (writeOut !== false) {
  1212. $.each(results, function (ndx, rslt) {
  1213. if (rslt["activeMasksetIndex"] == activeMasksetIndex) {
  1214. result = rslt;
  1215. return false;
  1216. }
  1217. });
  1218. if (result != undefined) {
  1219. var self = this;
  1220. setTimeout(function () { opts.onKeyValidation.call(self, result["result"], opts); }, 0);
  1221. if (getActiveMaskSet()["writeOutBuffer"] && result["result"] !== false) {
  1222. var buffer = getActiveBuffer();
  1223. var newCaretPosition;
  1224. if (checkval) {
  1225. newCaretPosition = undefined;
  1226. } else if (opts.numericInput) {
  1227. if (p > radixPosition) {
  1228. newCaretPosition = seekPrevious(minimalForwardPosition);
  1229. } else if (c == opts.radixPoint) {
  1230. newCaretPosition = minimalForwardPosition - 1;
  1231. } else newCaretPosition = seekPrevious(minimalForwardPosition - 1);
  1232. } else {
  1233. newCaretPosition = minimalForwardPosition;
  1234. }
  1235. writeBuffer(input, buffer, newCaretPosition);
  1236. if (checkval !== true) {
  1237. setTimeout(function () { //timeout needed for IE
  1238. if (isComplete(buffer) === true)
  1239. $input.trigger("complete");
  1240. skipInputEvent = true;
  1241. $input.trigger("input");
  1242. }, 0);
  1243. }
  1244. } else if (isSlctn) {
  1245. getActiveMaskSet()["buffer"] = getActiveMaskSet()["undoBuffer"].split('');
  1246. }
  1247. } else if (isSlctn) {
  1248. getActiveMaskSet()["buffer"] = getActiveMaskSet()["undoBuffer"].split('');
  1249. }
  1250. }
  1251. if (opts.showTooltip) { //update tooltip
  1252. $input.prop("title", getActiveMaskSet()["mask"]);
  1253. }
  1254. //needed for IE8 and below
  1255. if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false;
  1256. }
  1257. }
  1258. }
  1259. function keyupEvent(e) {
  1260. var $input = $(this), input = this, k = e.keyCode, buffer = getActiveBuffer();
  1261. opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup
  1262. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  1263. if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  1264. buffer = getActiveBufferTemplate().slice();
  1265. writeBuffer(input, buffer);
  1266. caret(input, 0);
  1267. valueOnFocus = getActiveBuffer().join('');
  1268. } else {
  1269. writeBuffer(input, buffer);
  1270. if (buffer.join('') == getActiveBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) {
  1271. caret(input, TranslatePosition(0));
  1272. $input.click();
  1273. } else
  1274. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  1275. }
  1276. }
  1277. }
  1278. function pasteEvent(e) {
  1279. if (skipInputEvent === true && e.type == "input") {
  1280. skipInputEvent = false;
  1281. return true;
  1282. }
  1283. var input = this, $input = $(input);
  1284. //paste event for IE8 and lower I guess ;-)
  1285. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1286. return true;
  1287. }
  1288. setTimeout(function () {
  1289. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, input._valueGet(), opts) : input._valueGet();
  1290. checkVal(input, false, false, pasteValue.split(''), true);
  1291. writeBuffer(input, getActiveBuffer());
  1292. if (isComplete(getActiveBuffer()) === true)
  1293. $input.trigger("complete");
  1294. $input.click();
  1295. }, 0);
  1296. }
  1297. //not used - attempt to support android
  1298. function mobileInputEvent(e) {
  1299. var input = this, $input = $(input);
  1300. //backspace in chrome32 only fires input event - detect & treat
  1301. var caretPos = caret(input),
  1302. currentValue = input._valueGet();
  1303. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getActiveBufferTemplate().join('')) + ")*"), "");
  1304. //correct caretposition for chrome
  1305. if (caretPos.begin > currentValue.length) {
  1306. caret(input, currentValue.length);
  1307. caretPos = caret(input);
  1308. }
  1309. if ((getActiveBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getActiveBuffer()[caretPos.begin]
  1310. && currentValue.charAt(caretPos.begin + 1) != getActiveBuffer()[caretPos.begin]
  1311. && !isMask(caretPos.begin)) {
  1312. e.keyCode = opts.keyCode.BACKSPACE;
  1313. keydownEvent.call(input, e);
  1314. } else { //nonnumerics don't fire keypress
  1315. checkVal(input, false, false, currentValue.split(''));
  1316. writeBuffer(input, getActiveBuffer());
  1317. if (isComplete(getActiveBuffer()) === true)
  1318. $input.trigger("complete");
  1319. $input.click();
  1320. }
  1321. e.preventDefault();
  1322. }
  1323. function mask(el) {
  1324. $el = $(el);
  1325. if ($el.is(":input")) {
  1326. //store tests & original buffer in the input element - used to get the unmasked value
  1327. $el.data('_inputmask', {
  1328. 'masksets': masksets,
  1329. 'activeMasksetIndex': activeMasksetIndex,
  1330. 'opts': opts,
  1331. 'isRTL': false
  1332. });
  1333. //show tooltip
  1334. if (opts.showTooltip) {
  1335. $el.prop("title", getActiveMaskSet()["mask"]);
  1336. }
  1337. //correct greedy setting if needed
  1338. getActiveMaskSet()['greedy'] = getActiveMaskSet()['greedy'] ? getActiveMaskSet()['greedy'] : getActiveMaskSet()['repeat'] == 0;
  1339. patchValueProperty(el);
  1340. if (opts.numericInput) opts.isNumeric = opts.numericInput;
  1341. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1342. $el.css("text-align", "right");
  1343. if (el.dir == "rtl" || opts.numericInput) {
  1344. el.dir = "ltr";
  1345. $el.removeAttr("dir");
  1346. var inputData = $el.data('_inputmask');
  1347. inputData['isRTL'] = true;
  1348. $el.data('_inputmask', inputData);
  1349. isRTL = true;
  1350. }
  1351. //unbind all events - to make sure that no other mask will interfere when re-masking
  1352. $el.unbind(".inputmask");
  1353. $el.removeClass('focus.inputmask');
  1354. //bind events
  1355. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1356. if (valueOnFocus != getActiveBuffer().join('')) {
  1357. $el.change();
  1358. }
  1359. }).bind('reset', function () {
  1360. setTimeout(function () {
  1361. $el.trigger("setvalue");
  1362. }, 0);
  1363. });
  1364. $el.bind("mouseenter.inputmask", function () {
  1365. var $input = $(this), input = this;
  1366. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  1367. if (input._valueGet() != getActiveBuffer().join('')) {
  1368. writeBuffer(input, getActiveBuffer());
  1369. }
  1370. }
  1371. }).bind("blur.inputmask", function () {
  1372. var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getActiveBuffer();
  1373. $input.removeClass('focus.inputmask');
  1374. if (valueOnFocus != getActiveBuffer().join('')) {
  1375. $input.change();
  1376. }
  1377. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1378. if (nptValue == getActiveBufferTemplate().join(''))
  1379. input._valueSet('');
  1380. else { //clearout optional tail of the mask
  1381. clearOptionalTail(input);
  1382. }
  1383. }
  1384. if (isComplete(buffer) === false) {
  1385. $input.trigger("incomplete");
  1386. if (opts.clearIncomplete) {
  1387. $.each(masksets, function (ndx, ms) {
  1388. if (typeof (ms) == "object") {
  1389. ms["buffer"] = undefined;
  1390. ms["validPositions"] = {};
  1391. }
  1392. });
  1393. activeMasksetIndex = 0;
  1394. if (opts.clearMaskOnLostFocus)
  1395. input._valueSet('');
  1396. else {
  1397. buffer = getActiveBufferTemplate().slice();
  1398. writeBuffer(input, buffer);
  1399. }
  1400. }
  1401. }
  1402. }).bind("focus.inputmask", function () {
  1403. var $input = $(this), input = this, nptValue = input._valueGet();
  1404. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1405. if (input._valueGet() != getActiveBuffer().join('')) {
  1406. writeBuffer(input, getActiveBuffer(), seekNext(getLastValidPosition()));
  1407. }
  1408. }
  1409. $input.addClass('focus.inputmask');
  1410. valueOnFocus = getActiveBuffer().join('');
  1411. }).bind("mouseleave.inputmask", function () {
  1412. var $input = $(this), input = this;
  1413. if (opts.clearMaskOnLostFocus) {
  1414. if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1415. if (input._valueGet() == getActiveBufferTemplate().join('') || input._valueGet() == '')
  1416. input._valueSet('');
  1417. else { //clearout optional tail of the mask
  1418. clearOptionalTail(input);
  1419. }
  1420. }
  1421. }
  1422. }).bind("click.inputmask", function () {
  1423. var input = this;
  1424. setTimeout(function () {
  1425. var selectedCaret = caret(input), buffer = getActiveBuffer();
  1426. if (selectedCaret.begin == selectedCaret.end) {
  1427. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1428. lvp = getLastValidPosition(undefined, clickPosition),
  1429. lastPosition;
  1430. if (opts.isNumeric) {
  1431. lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
  1432. (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
  1433. seekNext(lvp);
  1434. } else {
  1435. lastPosition = seekNext(lvp);
  1436. }
  1437. if (clickPosition < lastPosition) {
  1438. if (isMask(clickPosition))
  1439. caret(input, clickPosition);
  1440. else caret(input, seekNext(clickPosition));
  1441. } else
  1442. caret(input, lastPosition);
  1443. }
  1444. }, 0);
  1445. }).bind('dblclick.inputmask', function () {
  1446. var input = this;
  1447. setTimeout(function () {
  1448. caret(input, 0, seekNext(getLastValidPosition()));
  1449. }, 0);
  1450. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1451. ).bind('setvalue.inputmask', function () {
  1452. var input = this;
  1453. checkVal(input, true);
  1454. valueOnFocus = getActiveBuffer().join('');
  1455. if (input._valueGet() == getActiveBufferTemplate().join(''))
  1456. input._valueSet('');
  1457. }).bind('complete.inputmask', opts.oncomplete
  1458. ).bind('incomplete.inputmask', opts.onincomplete
  1459. ).bind('cleared.inputmask', opts.oncleared);
  1460. $el.bind("keydown.inputmask", keydownEvent
  1461. ).bind("keypress.inputmask", keypressEvent
  1462. ).bind("keyup.inputmask", keyupEvent);
  1463. // as the other inputevents aren't reliable for the moment we only base on the input event
  1464. // needs follow-up
  1465. if (android || androidfirefox || androidchrome || kindle) {
  1466. $el.attr("autocomplete", "off")
  1467. .attr("autocorrect", "off")
  1468. .attr("autocapitalize", "off")
  1469. .attr("spellcheck", false);
  1470. if (androidfirefox || kindle) {
  1471. $el.unbind("keydown.inputmask", keydownEvent
  1472. ).unbind("keypress.inputmask", keypressEvent
  1473. ).unbind("keyup.inputmask", keyupEvent);
  1474. if (PasteEventType == "input") {
  1475. $el.unbind(PasteEventType + ".inputmask");
  1476. }
  1477. $el.bind("input.inputmask", mobileInputEvent);
  1478. }
  1479. }
  1480. if (msie1x)
  1481. $el.bind("input.inputmask", pasteEvent);
  1482. //apply mask
  1483. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1484. checkVal(el, true, false, initialValue.split(''));
  1485. valueOnFocus = getActiveBuffer().join('');
  1486. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1487. var activeElement;
  1488. try {
  1489. activeElement = document.activeElement;
  1490. } catch (e) {
  1491. }
  1492. if (activeElement === el) { //position the caret when in focus
  1493. $el.addClass('focus.inputmask');
  1494. caret(el, seekNext(getLastValidPosition()));
  1495. } else if (opts.clearMaskOnLostFocus) {
  1496. if (getActiveBuffer().join('') == getActiveBufferTemplate().join('')) {
  1497. el._valueSet('');
  1498. } else {
  1499. clearOptionalTail(el);
  1500. }
  1501. } else {
  1502. writeBuffer(el, getActiveBuffer());
  1503. }
  1504. installEventRuler(el);
  1505. }
  1506. }
  1507. //action object
  1508. if (actionObj != undefined) {
  1509. switch (actionObj["action"]) {
  1510. case "isComplete":
  1511. return isComplete(actionObj["buffer"]);
  1512. case "unmaskedvalue":
  1513. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1514. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1515. case "mask":
  1516. mask(actionObj["el"]);
  1517. break;
  1518. case "format":
  1519. $el = $({});
  1520. $el.data('_inputmask', {
  1521. 'masksets': masksets,
  1522. 'activeMasksetIndex': activeMasksetIndex,
  1523. 'opts': opts,
  1524. 'isRTL': opts.numericInput
  1525. });
  1526. if (opts.numericInput) {
  1527. opts.isNumeric = opts.numericInput;
  1528. isRTL = true;
  1529. }
  1530. checkVal($el, false, false, actionObj["value"].split(''));
  1531. return getActiveBuffer().join('');
  1532. case "isValid":
  1533. $el = $({});
  1534. $el.data('_inputmask', {
  1535. 'masksets': masksets,
  1536. 'activeMasksetIndex': activeMasksetIndex,
  1537. 'opts': opts,
  1538. 'isRTL': opts.numericInput
  1539. });
  1540. if (opts.numericInput) {
  1541. opts.isNumeric = opts.numericInput;
  1542. isRTL = true;
  1543. }
  1544. checkVal($el, false, true, actionObj["value"].split(''));
  1545. return isComplete(getActiveBuffer());
  1546. }
  1547. }
  1548. };
  1549. $.inputmask = {
  1550. //options default
  1551. defaults: {
  1552. placeholder: "_",
  1553. optionalmarker: { start: "[", end: "]" },
  1554. quantifiermarker: { start: "{", end: "}" },
  1555. groupmarker: { start: "(", end: ")" },
  1556. escapeChar: "\\",
  1557. mask: null,
  1558. oncomplete: $.noop, //executes when the mask is complete
  1559. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1560. oncleared: $.noop, //executes when the mask is cleared
  1561. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1562. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1563. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1564. clearMaskOnLostFocus: true,
  1565. insertMode: true, //insert the input or overwrite the input
  1566. clearIncomplete: false, //clear the incomplete input on blur
  1567. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1568. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  1569. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  1570. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1571. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1572. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1573. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1574. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1575. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1576. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1577. showTooltip: false, //show the activemask as tooltip
  1578. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1579. //numeric basic properties
  1580. isNumeric: false, //enable numeric features
  1581. radixPoint: "", //".", // | ","
  1582. skipRadixDance: false, //disable radixpoint caret positioning
  1583. rightAlignNumerics: true, //align numerics to the right
  1584. //numeric basic properties
  1585. definitions: {
  1586. '9': {
  1587. validator: "[0-9]",
  1588. cardinality: 1,
  1589. definitionSymbol: "*"
  1590. },
  1591. 'a': {
  1592. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1593. cardinality: 1,
  1594. definitionSymbol: "*"
  1595. },
  1596. '*': {
  1597. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1598. cardinality: 1
  1599. }
  1600. },
  1601. keyCode: {
  1602. 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,
  1603. 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
  1604. },
  1605. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1606. 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],
  1607. isComplete: undefined //override for isComplete - args => buffer, opts - return true || false
  1608. },
  1609. escapeRegex: function (str) {
  1610. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1611. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1612. },
  1613. format: function (value, options) {
  1614. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1615. resolveAlias(opts.alias, options, opts);
  1616. return maskScope(generateMaskSets(opts), 0, opts, { "action": "format", "value": value });
  1617. },
  1618. isValid: function (value, options) {
  1619. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1620. resolveAlias(opts.alias, options, opts);
  1621. return maskScope(generateMaskSets(opts), 0, opts, { "action": "isValid", "value": value });
  1622. }
  1623. };
  1624. $.fn.inputmask = function (fn, options) {
  1625. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1626. masksets,
  1627. activeMasksetIndex = 0;
  1628. if (typeof fn === "string") {
  1629. switch (fn) {
  1630. case "mask":
  1631. //resolve possible aliases given by options
  1632. resolveAlias(opts.alias, options, opts);
  1633. masksets = generateMaskSets(opts);
  1634. if (masksets.length == 0) { return this; }
  1635. return this.each(function () {
  1636. maskScope($.extend(true, {}, masksets), 0, opts, { "action": "mask", "el": this });
  1637. });
  1638. case "unmaskedvalue":
  1639. var $input = $(this), input = this;
  1640. if ($input.data('_inputmask')) {
  1641. masksets = $input.data('_inputmask')['masksets'];
  1642. activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
  1643. opts = $input.data('_inputmask')['opts'];
  1644. return maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input });
  1645. } else return $input.val();
  1646. case "remove":
  1647. return this.each(function () {
  1648. var $input = $(this), input = this;
  1649. if ($input.data('_inputmask')) {
  1650. masksets = $input.data('_inputmask')['masksets'];
  1651. activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
  1652. opts = $input.data('_inputmask')['opts'];
  1653. //writeout the unmaskedvalue
  1654. input._valueSet(maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true }));
  1655. //clear data
  1656. $input.removeData('_inputmask');
  1657. //unbind all events
  1658. $input.unbind(".inputmask");
  1659. $input.removeClass('focus.inputmask');
  1660. //restore the value property
  1661. var valueProperty;
  1662. if (Object.getOwnPropertyDescriptor)
  1663. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  1664. if (valueProperty && valueProperty.get) {
  1665. if (input._valueGet) {
  1666. Object.defineProperty(input, "value", {
  1667. get: input._valueGet,
  1668. set: input._valueSet
  1669. });
  1670. }
  1671. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  1672. if (input._valueGet) {
  1673. input.__defineGetter__("value", input._valueGet);
  1674. input.__defineSetter__("value", input._valueSet);
  1675. }
  1676. }
  1677. try { //try catch needed for IE7 as it does not supports deleting fns
  1678. delete input._valueGet;
  1679. delete input._valueSet;
  1680. } catch (e) {
  1681. input._valueGet = undefined;
  1682. input._valueSet = undefined;
  1683. }
  1684. }
  1685. });
  1686. break;
  1687. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1688. if (this.data('_inputmask')) {
  1689. masksets = this.data('_inputmask')['masksets'];
  1690. activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
  1691. return masksets[activeMasksetIndex]['_buffer'].join('');
  1692. }
  1693. else return "";
  1694. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1695. return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
  1696. case "isComplete":
  1697. masksets = this.data('_inputmask')['masksets'];
  1698. activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
  1699. opts = this.data('_inputmask')['opts'];
  1700. return maskScope(masksets, activeMasksetIndex, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split('') });
  1701. case "getmetadata": //return mask metadata if exists
  1702. if (this.data('_inputmask')) {
  1703. masksets = this.data('_inputmask')['masksets'];
  1704. activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
  1705. return masksets[activeMasksetIndex]['metadata'];
  1706. }
  1707. else return undefined;
  1708. default:
  1709. //check if the fn is an alias
  1710. if (!resolveAlias(fn, options, opts)) {
  1711. //maybe fn is a mask so we try
  1712. //set mask
  1713. opts.mask = fn;
  1714. }
  1715. masksets = generateMaskSets(opts);
  1716. if (masksets.length == 0) { return this; }
  1717. return this.each(function () {
  1718. maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this });
  1719. });
  1720. break;
  1721. }
  1722. } else if (typeof fn == "object") {
  1723. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1724. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1725. masksets = generateMaskSets(opts);
  1726. if (masksets.length == 0) { return this; }
  1727. return this.each(function () {
  1728. maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this });
  1729. });
  1730. } else if (fn == undefined) {
  1731. //look for data-inputmask atribute - the attribute should only contain optipns
  1732. return this.each(function () {
  1733. var attrOptions = $(this).attr("data-inputmask");
  1734. if (attrOptions && attrOptions != "") {
  1735. try {
  1736. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1737. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1738. $.extend(true, dataoptions, options);
  1739. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1740. resolveAlias(opts.alias, dataoptions, opts);
  1741. opts.alias = undefined;
  1742. $(this).inputmask(opts);
  1743. } catch (ex) { } //need a more relax parseJSON
  1744. }
  1745. });
  1746. }
  1747. };
  1748. }
  1749. })(jQuery);