jquery.inputmask.js 111 KB

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