jquery.inputmask.js 130 KB

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