jquery.inputmask.js 121 KB

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