jquery.inputmask.js 119 KB

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