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