jquery.inputmask.js 111 KB

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