jquery.inputmask.js 120 KB

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