jquery.inputmask.js 111 KB

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