jquery.inputmask.js 130 KB

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