jquery.inputmask.js 106 KB

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