jquery.inputmask.js 130 KB

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