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 = (before != -1 && (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, event, triggerInputEvent) {
  915. if (event && $.isFunction(opts.onBeforeWrite)) {
  916. var result = opts.onBeforeWrite.call(input, event, buffer, caretPos, opts);
  917. if (result && result["refreshFromBuffer"]) {
  918. var refresh = result["refreshFromBuffer"];
  919. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], result["buffer"]);
  920. resetMaskSet(true);
  921. caretPos = result.caret || caretPos;
  922. }
  923. }
  924. input._valueSet(buffer.join(''));
  925. if (caretPos != undefined) {
  926. caret(input, caretPos);
  927. }
  928. if (triggerInputEvent === true) {
  929. skipInputEvent = true;
  930. $(input).trigger("input");
  931. }
  932. }
  933. function getPlaceholder(pos, test) {
  934. test = test || getTest(pos);
  935. return test["placeholder"] != undefined ? test["placeholder"] : (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  936. }
  937. function checkVal(input, writeOut, strict, nptvl) {
  938. function isTemplateMatch() {
  939. var isMatch = false;
  940. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join('').indexOf(charCodes);
  941. if (charCodeNdx != -1 && !isMask(initialNdx)) {
  942. isMatch = true;
  943. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  944. for (var i = 0; i < bufferTemplateArr.length; i++) {
  945. if (bufferTemplateArr[i] != " ") {
  946. isMatch = false; break;
  947. }
  948. }
  949. }
  950. return isMatch;
  951. }
  952. var inputValue = nptvl != undefined ? nptvl.slice() : input._valueGet().split('');
  953. resetMaskSet();
  954. getMaskSet()["p"] = seekNext(-1);
  955. if (writeOut) input._valueSet(""); //initial clear
  956. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(''), matches = inputValue.join('').match(new RegExp(escapeRegex(staticInput), "g"));
  957. if (matches && matches.length > 0) {
  958. inputValue.splice(0, staticInput.length * matches.length);
  959. }
  960. var charCodes = "", initialNdx = 0;
  961. $.each(inputValue, function (ndx, charCode) {
  962. console.log("checkval " + charCode);
  963. var keypress = $.Event("keypress");
  964. keypress.which = charCode.charCodeAt(0);
  965. charCodes += charCode;
  966. var lvp = getLastValidPosition(), lvTest = getMaskSet()["validPositions"][lvp], nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  967. if (!isTemplateMatch() || strict) {
  968. var pos = strict ? ndx : (nextTest["match"].fn == null && nextTest["match"].optionality && (lvp + 1) < getMaskSet()["p"] ? lvp + 1 : getMaskSet()["p"]);
  969. keypressEvent.call(input, keypress, true, false, strict, pos);
  970. initialNdx = pos + 1;
  971. charCodes = "";
  972. } else {
  973. keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  974. }
  975. });
  976. if (writeOut) {
  977. writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined, $.Event("checkval"));
  978. }
  979. }
  980. function escapeRegex(str) {
  981. return $.inputmask.escapeRegex.call(this, str);
  982. }
  983. function unmaskedvalue($input) {
  984. if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
  985. var umValue = [], vps = getMaskSet()["validPositions"];
  986. for (var pndx in vps) {
  987. if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
  988. umValue.push(vps[pndx]["input"]);
  989. }
  990. }
  991. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  992. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join('');
  993. if ($.isFunction(opts.onUnMask)) {
  994. unmaskedValue = (opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue);
  995. }
  996. return unmaskedValue;
  997. } else {
  998. return $input[0]._valueGet();
  999. }
  1000. }
  1001. function TranslatePosition(pos) {
  1002. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  1003. var bffrLght = getBuffer().length;
  1004. pos = bffrLght - pos;
  1005. }
  1006. return pos;
  1007. }
  1008. function caret(input, begin, end) {
  1009. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  1010. if (typeof begin == 'number') {
  1011. begin = TranslatePosition(begin);
  1012. end = TranslatePosition(end);
  1013. end = (typeof end == 'number') ? end : begin;
  1014. //store caret for multi scope
  1015. var data = $(npt).data('_inputmask') || {};
  1016. data["caret"] = { "begin": begin, "end": end };
  1017. $(npt).data('_inputmask', data);
  1018. if (!$(npt).is(":visible")) {
  1019. return;
  1020. }
  1021. var scrollCalc = $(npt).css("font-size").replace("px", "") * end;
  1022. npt.scrollLeft = scrollCalc > npt.scrollWidth ? scrollCalc : 0;
  1023. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  1024. if (npt.setSelectionRange) {
  1025. npt.selectionStart = begin;
  1026. npt.selectionEnd = end;
  1027. } else if (npt.createTextRange) {
  1028. range = npt.createTextRange();
  1029. range.collapse(true);
  1030. range.moveEnd('character', end);
  1031. range.moveStart('character', begin);
  1032. range.select();
  1033. }
  1034. } else {
  1035. var data = $(npt).data('_inputmask');
  1036. if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
  1037. begin = data["caret"]["begin"];
  1038. end = data["caret"]["end"];
  1039. } else if (npt.setSelectionRange) {
  1040. begin = npt.selectionStart;
  1041. end = npt.selectionEnd;
  1042. } else if (document.selection && document.selection.createRange) {
  1043. range = document.selection.createRange();
  1044. begin = 0 - range.duplicate().moveStart('character', -100000);
  1045. end = begin + range.text.length;
  1046. }
  1047. begin = TranslatePosition(begin);
  1048. end = TranslatePosition(end);
  1049. return { "begin": begin, "end": end };
  1050. }
  1051. }
  1052. function determineLastRequiredPosition(returnDefinition) {
  1053. var buffer = getBuffer(), bl = buffer.length,
  1054. pos, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet()["validPositions"][lvp],
  1055. ndxIntlzr = lvTest != undefined ? lvTest["locator"].slice() : undefined, testPos;
  1056. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1057. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1058. ndxIntlzr = testPos["locator"].slice();
  1059. positions[pos] = $.extend(true, {}, testPos);
  1060. }
  1061. var lvTestAltArr = lvTest && lvTest.alternation != undefined ? lvTest["locator"][lvTest.alternation].split(",") : [];
  1062. for (pos = bl - 1; pos > lvp; pos--) {
  1063. testPos = positions[pos]["match"];
  1064. if ((testPos.optionality ||
  1065. testPos.optionalQuantifier ||
  1066. (lvTest && lvTest.alternation != undefined && positions[pos]["locator"][lvTest.alternation] != undefined && $.inArray(positions[pos]["locator"][lvTest.alternation].toString(), lvTestAltArr) != -1))
  1067. && buffer[pos] == getPlaceholder(pos, testPos)) {
  1068. bl--;
  1069. } else break;
  1070. }
  1071. return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
  1072. }
  1073. function clearOptionalTail(buffer) {
  1074. var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
  1075. for (; lmib > rl; lmib--) {
  1076. if (isMask(lmib)) break; //fixme ismask is not good enough
  1077. }
  1078. buffer.splice(rl, lmib + 1 - rl);
  1079. }
  1080. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1081. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  1082. if (opts.repeat == "*") return undefined;
  1083. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
  1084. if (lvp == aml) {
  1085. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
  1086. complete = true;
  1087. for (var i = 0; i <= aml; i++) {
  1088. var mask = isMask(i);
  1089. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  1090. complete = false;
  1091. break;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. return complete;
  1097. }
  1098. function isSelection(begin, end) {
  1099. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  1100. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  1101. }
  1102. function installEventRuler(npt) {
  1103. var events = $._data(npt).events;
  1104. $.each(events, function (eventType, eventHandlers) {
  1105. $.each(eventHandlers, function (ndx, eventHandler) {
  1106. if (eventHandler.namespace == "inputmask") {
  1107. if (eventHandler.type != "setvalue") {
  1108. var handler = eventHandler.handler;
  1109. eventHandler.handler = function (e) {
  1110. //console.log("triggered " + e.type);
  1111. if (this.disabled || (this.readOnly && !(e.type == "keydown" && e.ctrlKey && e.keyCode == 67)))
  1112. e.preventDefault();
  1113. else {
  1114. switch (e.type) {
  1115. case "input":
  1116. if (skipInputEvent === true) {
  1117. skipInputEvent = false;
  1118. return e.preventDefault();
  1119. }
  1120. break;
  1121. case "keydown":
  1122. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1123. skipKeyPressEvent = false;
  1124. break;
  1125. case "keypress":
  1126. if (skipKeyPressEvent === true)
  1127. return e.preventDefault();
  1128. skipKeyPressEvent = true;
  1129. break;
  1130. case "compositionstart":
  1131. break;
  1132. case "compositionupdate":
  1133. skipInputEvent = true;
  1134. break;
  1135. case "compositionend":
  1136. break;
  1137. }
  1138. //console.log("executed " + e.type);
  1139. return handler.apply(this, arguments);
  1140. }
  1141. };
  1142. }
  1143. }
  1144. });
  1145. });
  1146. }
  1147. function patchValueProperty(npt) {
  1148. var valueGet;
  1149. var valueSet;
  1150. function PatchValhook(type) {
  1151. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  1152. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  1153. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1154. elem.value = value;
  1155. return elem;
  1156. };
  1157. $.valHooks[type] = {
  1158. get: function (elem) {
  1159. var $elem = $(elem);
  1160. if ($elem.data('_inputmask')) {
  1161. if ($elem.data('_inputmask')['opts'].autoUnmask)
  1162. return $elem.inputmask('unmaskedvalue');
  1163. else {
  1164. var result = valhookGet(elem),
  1165. inputData = $elem.data('_inputmask'),
  1166. maskset = inputData['maskset'],
  1167. bufferTemplate = maskset['_buffer'];
  1168. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  1169. return result != bufferTemplate ? result : '';
  1170. }
  1171. } else return valhookGet(elem);
  1172. },
  1173. set: function (elem, value) {
  1174. var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
  1175. if (inputData) {
  1176. result = valhookSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value);
  1177. $elem.triggerHandler('setvalue.inputmask');
  1178. } else {
  1179. result = valhookSet(elem, value);
  1180. }
  1181. return result;
  1182. },
  1183. inputmaskpatch: true
  1184. };
  1185. }
  1186. }
  1187. function getter() {
  1188. var $self = $(this), inputData = $(this).data('_inputmask');
  1189. if (inputData) {
  1190. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  1191. } else return valueGet.call(this);
  1192. }
  1193. function setter(value) {
  1194. var inputData = $(this).data('_inputmask');
  1195. if (inputData) {
  1196. valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value);
  1197. $(this).triggerHandler('setvalue.inputmask');
  1198. } else {
  1199. valueSet.call(this, value);
  1200. }
  1201. }
  1202. function InstallNativeValueSetFallback(npt) {
  1203. $(npt).bind("mouseenter.inputmask", function (event) {
  1204. var $input = $(this), input = this, value = input._valueGet();
  1205. if (value != "" && value != getBuffer().join('')) {
  1206. this._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, value, opts) || value) : value);
  1207. $input.triggerHandler('setvalue.inputmask');
  1208. }
  1209. });
  1210. //!! the bound handlers are executed in the order they where bound
  1211. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1212. var events = $._data(npt).events;
  1213. var handlers = events["mouseover"];
  1214. if (handlers) {
  1215. var ourHandler = handlers[handlers.length - 1];
  1216. for (var i = handlers.length - 1; i > 0; i--) {
  1217. handlers[i] = handlers[i - 1];
  1218. }
  1219. handlers[0] = ourHandler;
  1220. }
  1221. }
  1222. if (!npt._valueGet) {
  1223. //var valueProperty;
  1224. if (Object.getOwnPropertyDescriptor)
  1225. var valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  1226. if (valueProperty && valueProperty.configurable && false) { //experimental for chrome
  1227. npt._value = valueProperty.value;
  1228. valueGet = function () {
  1229. return this._value || "";
  1230. }
  1231. valueSet = function (value) {
  1232. this._value = value;
  1233. this.select();
  1234. this.setRangeText(value);
  1235. this.selectionStart = this.selectionEnd;
  1236. }
  1237. Object.defineProperty(npt, "value", {
  1238. get: getter,
  1239. set: setter
  1240. });
  1241. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1242. valueGet = npt.__lookupGetter__("value");
  1243. valueSet = npt.__lookupSetter__("value");
  1244. npt.__defineGetter__("value", getter);
  1245. npt.__defineSetter__("value", setter);
  1246. } else { //jquery.val
  1247. valueGet = function () { return npt.value; }
  1248. valueSet = function (value) { npt.value = value; }
  1249. PatchValhook(npt.type);
  1250. InstallNativeValueSetFallback(npt);
  1251. }
  1252. npt._valueGet = function (overruleRTL) {
  1253. return isRTL && overruleRTL !== true ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  1254. };
  1255. npt._valueSet = function (value) {
  1256. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  1257. };
  1258. }
  1259. }
  1260. function handleRemove(input, k, pos) {
  1261. function generalize() {
  1262. if (opts.keepStatic) {
  1263. resetMaskSet(true);
  1264. var validInputs = [],
  1265. lastAlt;
  1266. //find last alternation
  1267. for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) {
  1268. if (getMaskSet()["validPositions"][lastAlt]) {
  1269. if (getMaskSet()["validPositions"][lastAlt].alternation != undefined) {
  1270. break;
  1271. }
  1272. validInputs.push(getMaskSet()["validPositions"][lastAlt].input);
  1273. delete getMaskSet()["validPositions"][lastAlt];
  1274. }
  1275. }
  1276. if (lastAlt > 0) {
  1277. while (validInputs.length > 0) {
  1278. getMaskSet()["p"] = seekNext(getLastValidPosition());
  1279. var keypress = $.Event("keypress");
  1280. keypress.which = validInputs.pop().charCodeAt(0);
  1281. keypressEvent.call(input, keypress, true, false, false, getMaskSet()["p"]);
  1282. }
  1283. }
  1284. }
  1285. }
  1286. if (opts.numericInput || isRTL) {
  1287. if (k == $.inputmask.keyCode.BACKSPACE)
  1288. k = $.inputmask.keyCode.DELETE;
  1289. else if (k == $.inputmask.keyCode.DELETE)
  1290. k = $.inputmask.keyCode.BACKSPACE;
  1291. if (isRTL) {
  1292. var pend = pos.end;
  1293. pos.end = pos.begin;
  1294. pos.begin = pend;
  1295. }
  1296. }
  1297. if (k == $.inputmask.keyCode.BACKSPACE && pos.end - pos.begin <= 1)
  1298. pos.begin = seekPrevious(pos.begin);
  1299. else if (k == $.inputmask.keyCode.DELETE && pos.begin == pos.end)
  1300. pos.end++;
  1301. stripValidPositions(pos.begin, pos.end);
  1302. generalize(); //revert the alternation
  1303. var firstMaskedPos = getLastValidPosition(pos.begin);
  1304. if (firstMaskedPos < pos.begin) {
  1305. if (firstMaskedPos == -1) resetMaskSet();
  1306. getMaskSet()["p"] = seekNext(firstMaskedPos);
  1307. } else {
  1308. getMaskSet()["p"] = pos.begin;
  1309. }
  1310. }
  1311. //postprocessing of the validpositions according to the buffer manipulations
  1312. function handleOnKeyResult(input, keyResult, caretPos) {
  1313. if (keyResult && keyResult["refreshFromBuffer"]) {
  1314. var refresh = keyResult["refreshFromBuffer"];
  1315. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], keyResult["buffer"]);
  1316. resetMaskSet(true);
  1317. if (caretPos != undefined) {
  1318. writeBuffer(input, getBuffer());
  1319. caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
  1320. }
  1321. }
  1322. }
  1323. function keydownEvent(e) {
  1324. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1325. //backspace, delete, and escape get special treatment
  1326. if (k == $.inputmask.keyCode.BACKSPACE || k == $.inputmask.keyCode.DELETE || (iphone && k == 127) || (e.ctrlKey && k == 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1327. e.preventDefault(); //stop default action but allow propagation
  1328. if (k == 88) undoValue = getBuffer().join('');
  1329. handleRemove(input, k, pos);
  1330. writeBuffer(input, getBuffer(), getMaskSet()["p"], e, undoValue != getBuffer().join(''));
  1331. if (input._valueGet() == getBufferTemplate().join(''))
  1332. $input.trigger('cleared');
  1333. if (opts.showTooltip) { //update tooltip
  1334. $input.prop("title", getMaskSet()["mask"]);
  1335. }
  1336. } else if (k == $.inputmask.keyCode.END || k == $.inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1337. setTimeout(function () {
  1338. var caretPos = seekNext(getLastValidPosition());
  1339. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1340. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1341. }, 0);
  1342. } else if ((k == $.inputmask.keyCode.HOME && !e.shiftKey) || k == $.inputmask.keyCode.PAGE_UP) { //Home or page_up
  1343. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1344. } else if ((opts.undoOnEscape && k == $.inputmask.keyCode.ESCAPE) || (k == 90 && e.ctrlKey)) { //escape && undo
  1345. checkVal(input, true, false, undoValue.split(''));
  1346. $input.click();
  1347. } else if (k == $.inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1348. opts.insertMode = !opts.insertMode;
  1349. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1350. } else if (opts.insertMode == false && !e.shiftKey) {
  1351. if (k == $.inputmask.keyCode.RIGHT) {
  1352. setTimeout(function () {
  1353. var caretPos = caret(input);
  1354. caret(input, caretPos.begin);
  1355. }, 0);
  1356. } else if (k == $.inputmask.keyCode.LEFT) {
  1357. setTimeout(function () {
  1358. var caretPos = caret(input);
  1359. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1360. }, 0);
  1361. }
  1362. }
  1363. ignorable = $.inArray(k, opts.ignorables) != -1;
  1364. }
  1365. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  1366. var input = this, $input = $(input);
  1367. var k = e.which || e.charCode || e.keyCode;
  1368. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1369. return true;
  1370. } else {
  1371. if (k) {
  1372. //special treat the decimal separator
  1373. if (k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1374. var pos = checkval ? { begin: ndx, end: ndx } : caret(input), forwardPosition, c = String.fromCharCode(k);
  1375. //should we clear a possible selection??
  1376. var isSlctn = isSelection(pos.begin, pos.end);
  1377. if (isSlctn) {
  1378. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1379. handleRemove(input, $.inputmask.keyCode.DELETE, pos);
  1380. if (!opts.insertMode) { //preserve some space
  1381. opts.insertMode = !opts.insertMode;
  1382. setValidPosition(pos.begin, strict);
  1383. opts.insertMode = !opts.insertMode;
  1384. }
  1385. isSlctn = !opts.multi;
  1386. }
  1387. getMaskSet()["writeOutBuffer"] = true;
  1388. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1389. var valResult = isValid(p, c, strict);
  1390. if (valResult !== false) {
  1391. if (valResult !== true) {
  1392. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1393. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1394. }
  1395. resetMaskSet(true);
  1396. if (valResult.caret != undefined)
  1397. forwardPosition = valResult.caret;
  1398. else {
  1399. var vps = getMaskSet()["validPositions"];
  1400. if (!opts.keepStatic && (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation != undefined))
  1401. forwardPosition = p + 1;
  1402. else
  1403. forwardPosition = seekNext(p);
  1404. }
  1405. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1406. }
  1407. if (writeOut !== false) {
  1408. var self = this;
  1409. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  1410. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1411. var buffer = getBuffer();
  1412. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  1413. if (checkval !== true) {
  1414. setTimeout(function () { //timeout needed for IE
  1415. if (isComplete(buffer) === true)
  1416. $input.trigger("complete");
  1417. }, 0);
  1418. }
  1419. } else if (isSlctn) {
  1420. getMaskSet()["buffer"] = undefined;
  1421. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1422. }
  1423. } else if (isSlctn) {
  1424. getMaskSet()["buffer"] = undefined;
  1425. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1426. }
  1427. if (opts.showTooltip) { //update tooltip
  1428. $input.prop("title", getMaskSet()["mask"]);
  1429. }
  1430. if (checkval && $.isFunction(opts.onBeforeWrite)) {
  1431. var result = opts.onBeforeWrite.call(this, e, getBuffer(), forwardPosition, opts);
  1432. if (result && result["refreshFromBuffer"]) {
  1433. var refresh = result["refreshFromBuffer"];
  1434. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], result["buffer"]);
  1435. resetMaskSet(true);
  1436. if (result.caret) {
  1437. getMaskSet()["p"] = result.caret;
  1438. }
  1439. }
  1440. }
  1441. e.preventDefault();
  1442. }
  1443. }
  1444. }
  1445. function keyupEvent(e) {
  1446. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  1447. opts.onKeyUp.call(this, e, buffer, opts);
  1448. }
  1449. function pasteEvent(e) {
  1450. var input = this, $input = $(input), inputValue = input._valueGet(true), caretPos = caret(input);
  1451. //paste event for IE8 and lower I guess ;-)
  1452. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1453. return true;
  1454. } else if (e.type == "paste") {
  1455. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  1456. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  1457. if (valueBeforeCaret == getBufferTemplate().slice(0, caretPos.begin).join('')) valueBeforeCaret = "";
  1458. if (valueAfterCaret == getBufferTemplate().slice(caretPos.end).join('')) valueAfterCaret = "";
  1459. if (window.clipboardData && window.clipboardData.getData) { // IE
  1460. inputValue = valueBeforeCaret + window.clipboardData.getData('Text') + valueAfterCaret;
  1461. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  1462. inputValue = valueBeforeCaret + e.originalEvent.clipboardData.getData('text/plain') + valueAfterCaret;
  1463. }
  1464. }
  1465. var pasteValue = $.isFunction(opts.onBeforePaste) ? (opts.onBeforePaste.call(input, inputValue, opts) || inputValue) : inputValue;
  1466. checkVal(input, true, false, isRTL ? pasteValue.split('').reverse() : pasteValue.split(''));
  1467. $input.click();
  1468. if (isComplete(getBuffer()) === true)
  1469. $input.trigger("complete");
  1470. return false;
  1471. }
  1472. //function mobileInputEvent(e) {
  1473. // var input = this;
  1474. // //backspace in chrome32 only fires input event - detect & treat
  1475. // var caretPos = caret(input),
  1476. // currentValue = input._valueGet();
  1477. // currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1478. // //correct caretposition for chrome
  1479. // if (caretPos.begin > currentValue.length) {
  1480. // caret(input, currentValue.length);
  1481. // caretPos = caret(input);
  1482. // }
  1483. // if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1484. // && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1485. // && !isMask(caretPos.begin)) {
  1486. // e.keyCode = $.inputmask.keyCode.BACKSPACE;
  1487. // keydownEvent.call(input, e);
  1488. // }
  1489. // e.preventDefault();
  1490. //}
  1491. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  1492. var input = this;
  1493. checkVal(input, true, false);
  1494. if (isComplete(getBuffer()) === true)
  1495. $(input).trigger("complete");
  1496. e.preventDefault();
  1497. }
  1498. function compositionStartEvent(e) {
  1499. var input = this;
  1500. undoValue = getBuffer().join('');
  1501. if (compositionData == "" || e.originalEvent.data.indexOf(compositionData) != 0) {
  1502. compositionCaretPos = caret(input);
  1503. }
  1504. }
  1505. function compositionUpdateEvent(e) {
  1506. var input = this, caretPos = compositionCaretPos || caret(input);
  1507. if (e.originalEvent.data.indexOf(compositionData) == 0) {
  1508. resetMaskSet();
  1509. caretPos = { begin: 0, end: 0 };
  1510. }
  1511. var newData = e.originalEvent.data;
  1512. caret(input, caretPos.begin, caretPos.end);
  1513. for (var i = 0; i < newData.length; i++) {
  1514. var keypress = $.Event("keypress");
  1515. keypress.which = newData.charCodeAt(i);
  1516. skipKeyPressEvent = false;
  1517. ignorable = false;
  1518. keypressEvent.call(input, keypress); //needs update
  1519. }
  1520. setTimeout(function () {
  1521. var forwardPosition = getMaskSet()["p"];
  1522. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1523. }, 0);
  1524. compositionData = e.originalEvent.data;
  1525. }
  1526. function compositionEndEvent(e) {
  1527. //pickup by inputfallback
  1528. }
  1529. function mask(el) {
  1530. $el = $(el);
  1531. if ($el.is(":input") && isInputTypeSupported($el.attr("type"))) {
  1532. //store tests & original buffer in the input element - used to get the unmasked value
  1533. $el.data('_inputmask', {
  1534. 'maskset': maskset,
  1535. 'opts': opts,
  1536. 'isRTL': false
  1537. });
  1538. //show tooltip
  1539. if (opts.showTooltip) {
  1540. $el.prop("title", getMaskSet()["mask"]);
  1541. }
  1542. if (el.dir == "rtl" || opts.rightAlign)
  1543. $el.css("text-align", "right");
  1544. if (el.dir == "rtl" || opts.numericInput) {
  1545. el.dir = "ltr";
  1546. $el.removeAttr("dir");
  1547. var inputData = $el.data('_inputmask');
  1548. inputData['isRTL'] = true;
  1549. $el.data('_inputmask', inputData);
  1550. isRTL = true;
  1551. }
  1552. //unbind all events - to make sure that no other mask will interfere when re-masking
  1553. $el.unbind(".inputmask");
  1554. //bind events
  1555. $el.closest('form').bind("submit", function (e) { //trigger change on submit if any
  1556. if (undoValue != getBuffer().join('')) {
  1557. $el.change();
  1558. }
  1559. if ($el[0]._valueGet && $el[0]._valueGet() == getBufferTemplate().join('')) {
  1560. $el[0]._valueSet(''); //clear masktemplete on submit and still has focus
  1561. }
  1562. if (opts.removeMaskOnSubmit) {
  1563. $el.inputmask("remove");
  1564. }
  1565. }).bind('reset', function () {
  1566. setTimeout(function () {
  1567. $el.triggerHandler('setvalue.inputmask');
  1568. }, 0);
  1569. });
  1570. $el.bind("mouseenter.inputmask", function () {
  1571. var $input = $(this), input = this;
  1572. if (!$input.is(":focus") && opts.showMaskOnHover) {
  1573. if (input._valueGet() != getBuffer().join('')) {
  1574. writeBuffer(input, getBuffer());
  1575. }
  1576. }
  1577. }).bind("blur.inputmask", function (e) {
  1578. var $input = $(this), input = this;
  1579. if ($input.data('_inputmask')) {
  1580. var nptValue = input._valueGet(), buffer = getBuffer().slice();
  1581. firstClick = true;
  1582. if (undoValue != buffer.join('')) {
  1583. $input.change();
  1584. undoValue = buffer.join('');
  1585. }
  1586. if (nptValue != '') {
  1587. if (opts.clearMaskOnLostFocus) {
  1588. if (nptValue == getBufferTemplate().join(''))
  1589. buffer = [];
  1590. else { //clearout optional tail of the mask
  1591. clearOptionalTail(buffer);
  1592. }
  1593. }
  1594. if (isComplete(buffer) === false) {
  1595. $input.trigger("incomplete");
  1596. if (opts.clearIncomplete) {
  1597. resetMaskSet();
  1598. if (opts.clearMaskOnLostFocus)
  1599. buffer = [];
  1600. else {
  1601. buffer = getBufferTemplate().slice();
  1602. }
  1603. }
  1604. }
  1605. writeBuffer(input, buffer, undefined, e);
  1606. }
  1607. }
  1608. }).bind("focus.inputmask", function (e) {
  1609. var $input = $(this), input = this, nptValue = input._valueGet();
  1610. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1611. if (input._valueGet() != getBuffer().join('')) {
  1612. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1613. }
  1614. }
  1615. undoValue = getBuffer().join('');
  1616. }).bind("mouseleave.inputmask", function () {
  1617. var $input = $(this), input = this;
  1618. if (opts.clearMaskOnLostFocus) {
  1619. var buffer = getBuffer().slice(), nptValue = input._valueGet();
  1620. if (!$input.is(":focus") && nptValue != $input.attr("placeholder") && nptValue != '') {
  1621. if (nptValue == getBufferTemplate().join(''))
  1622. buffer = [];
  1623. else { //clearout optional tail of the mask
  1624. clearOptionalTail(buffer);
  1625. }
  1626. writeBuffer(input, buffer);
  1627. }
  1628. }
  1629. }).bind("click.inputmask", function () {
  1630. var $input = $(this), input = this;
  1631. if ($input.is(":focus")) {
  1632. var selectedCaret = caret(input);
  1633. if (selectedCaret.begin == selectedCaret.end) {
  1634. if (opts.radixFocus && opts.radixPoint != "" && $.inArray(opts.radixPoint, getBuffer()) != -1 && (firstClick || getBuffer().join('') == getBufferTemplate().join(''))) {
  1635. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  1636. firstClick = false;
  1637. } else {
  1638. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1639. lastPosition = seekNext(getLastValidPosition(clickPosition));
  1640. if (clickPosition < lastPosition) {
  1641. caret(input, isMask(clickPosition) ? clickPosition : seekNext(clickPosition));
  1642. } else {
  1643. caret(input, lastPosition);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. }).bind('dblclick.inputmask', function () {
  1649. var input = this;
  1650. setTimeout(function () {
  1651. caret(input, 0, seekNext(getLastValidPosition()));
  1652. }, 0);
  1653. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1654. ).bind('setvalue.inputmask', function () {
  1655. var input = this;
  1656. checkVal(input, true, false);
  1657. undoValue = getBuffer().join('');
  1658. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input._valueGet() == getBufferTemplate().join(''))
  1659. input._valueSet('');
  1660. }).bind('cut.inputmask', function (e) {
  1661. skipInputEvent = true; //stop inputFallback
  1662. var input = this, $input = $(input), pos = caret(input);
  1663. handleRemove(input, $.inputmask.keyCode.DELETE, pos);
  1664. writeBuffer(input, getBuffer(), getMaskSet()["p"], e, undoValue != getBuffer().join(''));
  1665. if (input._valueGet() == getBufferTemplate().join(''))
  1666. $input.trigger('cleared');
  1667. if (opts.showTooltip) { //update tooltip
  1668. $input.prop("title", getMaskSet()["mask"]);
  1669. }
  1670. }).bind('complete.inputmask', opts.oncomplete
  1671. ).bind('incomplete.inputmask', opts.onincomplete
  1672. ).bind('cleared.inputmask', opts.oncleared);
  1673. $el.bind("keydown.inputmask", keydownEvent
  1674. ).bind("keypress.inputmask", keypressEvent
  1675. ).bind("keyup.inputmask", keyupEvent);
  1676. if (!androidfirefox) {
  1677. $el.bind("compositionstart.inputmask", compositionStartEvent
  1678. ).bind("compositionupdate.inputmask", compositionUpdateEvent
  1679. ).bind("compositionend.inputmask", compositionEndEvent);
  1680. }
  1681. if (PasteEventType === "paste") {
  1682. $el.bind("input.inputmask", inputFallBackEvent);
  1683. }
  1684. //if (android || androidfirefox || androidchrome || kindle) {
  1685. // $el.unbind("input.inputmask");
  1686. // $el.bind("input.inputmask", mobileInputEvent);
  1687. //}
  1688. patchValueProperty(el);
  1689. //apply mask
  1690. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el._valueGet(), opts) || el._valueGet()) : el._valueGet();
  1691. checkVal(el, true, false, initialValue.split(''));
  1692. var buffer = getBuffer().slice();
  1693. undoValue = buffer.join('');
  1694. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1695. var activeElement;
  1696. try {
  1697. activeElement = document.activeElement;
  1698. } catch (e) {
  1699. }
  1700. if (isComplete(buffer) === false) {
  1701. if (opts.clearIncomplete)
  1702. resetMaskSet();
  1703. }
  1704. if (opts.clearMaskOnLostFocus) {
  1705. if (buffer.join('') == getBufferTemplate().join('')) {
  1706. buffer = [];
  1707. } else {
  1708. clearOptionalTail(buffer);
  1709. }
  1710. }
  1711. writeBuffer(el, buffer);
  1712. if (activeElement === el) { //position the caret when in focus
  1713. caret(el, seekNext(getLastValidPosition()));
  1714. }
  1715. installEventRuler(el);
  1716. }
  1717. }
  1718. //action object
  1719. if (actionObj != undefined) {
  1720. switch (actionObj["action"]) {
  1721. case "isComplete":
  1722. $el = $(actionObj["el"]);
  1723. maskset = $el.data('_inputmask')['maskset'];
  1724. opts = $el.data('_inputmask')['opts'];
  1725. return isComplete(actionObj["buffer"]);
  1726. case "unmaskedvalue":
  1727. $el = actionObj["$input"];
  1728. maskset = $el.data('_inputmask')['maskset'];
  1729. opts = $el.data('_inputmask')['opts'];
  1730. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1731. return unmaskedvalue(actionObj["$input"]);
  1732. case "mask":
  1733. undoValue = getBuffer().join('');
  1734. mask(actionObj["el"]);
  1735. break;
  1736. case "format":
  1737. $el = $({});
  1738. $el.data('_inputmask', {
  1739. 'maskset': maskset,
  1740. 'opts': opts,
  1741. 'isRTL': opts.numericInput
  1742. });
  1743. if (opts.numericInput) {
  1744. isRTL = true;
  1745. }
  1746. var valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj["value"], opts) || actionObj["value"]) : actionObj["value"]).split('');
  1747. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  1748. $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  1749. if (actionObj["metadata"]) {
  1750. return {
  1751. value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''),
  1752. metadata: $el.inputmask("getmetadata")
  1753. }
  1754. }
  1755. return isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join('');
  1756. case "isValid":
  1757. $el = $({});
  1758. $el.data('_inputmask', {
  1759. 'maskset': maskset,
  1760. 'opts': opts,
  1761. 'isRTL': opts.numericInput
  1762. });
  1763. if (opts.numericInput) {
  1764. isRTL = true;
  1765. }
  1766. var valueBuffer = actionObj["value"].split('');
  1767. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1768. var buffer = getBuffer();
  1769. var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
  1770. for (; lmib > rl; lmib--) {
  1771. if (isMask(lmib)) break;
  1772. }
  1773. buffer.splice(rl, lmib + 1 - rl);
  1774. return isComplete(buffer) && actionObj["value"] == buffer.join('');
  1775. case "getemptymask":
  1776. $el = $(actionObj["el"]);
  1777. maskset = $el.data('_inputmask')['maskset'];
  1778. opts = $el.data('_inputmask')['opts'];
  1779. return getBufferTemplate();
  1780. case "remove":
  1781. var el = actionObj["el"];
  1782. $el = $(el);
  1783. maskset = $el.data('_inputmask')['maskset'];
  1784. opts = $el.data('_inputmask')['opts'];
  1785. //writeout the unmaskedvalue
  1786. el._valueSet(unmaskedvalue($el));
  1787. //unbind all events
  1788. $el.unbind(".inputmask");
  1789. //clear data
  1790. $el.removeData('_inputmask');
  1791. //restore the value property
  1792. var valueProperty;
  1793. if (Object.getOwnPropertyDescriptor)
  1794. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  1795. if (valueProperty && valueProperty.get) {
  1796. if (el._valueGet) {
  1797. Object.defineProperty(el, "value", {
  1798. get: el._valueGet,
  1799. set: el._valueSet
  1800. });
  1801. }
  1802. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  1803. if (el._valueGet) {
  1804. el.__defineGetter__("value", el._valueGet);
  1805. el.__defineSetter__("value", el._valueSet);
  1806. }
  1807. }
  1808. try { //try catch needed for IE7 as it does not supports deleting fns
  1809. delete el._valueGet;
  1810. delete el._valueSet;
  1811. } catch (e) {
  1812. el._valueGet = undefined;
  1813. el._valueSet = undefined;
  1814. }
  1815. break;
  1816. case "getmetadata":
  1817. $el = $(actionObj["el"]);
  1818. maskset = $el.data('_inputmask')['maskset'];
  1819. opts = $el.data('_inputmask')['opts'];
  1820. if ($.isArray(maskset["metadata"])) {
  1821. //find last alternation
  1822. var alternation, lvp = getLastValidPosition();
  1823. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  1824. if (getMaskSet()["validPositions"][firstAlt] && getMaskSet()["validPositions"][firstAlt].alternation != undefined) {
  1825. alternation = getMaskSet()["validPositions"][firstAlt].alternation;
  1826. break;
  1827. }
  1828. }
  1829. if (alternation != undefined) {
  1830. return maskset["metadata"][getMaskSet()["validPositions"][lvp].locator[alternation]];
  1831. } else return maskset["metadata"][0];
  1832. }
  1833. return maskset["metadata"];
  1834. }
  1835. }
  1836. }
  1837. $.inputmask = {
  1838. //options default
  1839. defaults: {
  1840. placeholder: "_",
  1841. optionalmarker: { start: "[", end: "]" },
  1842. quantifiermarker: { start: "{", end: "}" },
  1843. groupmarker: { start: "(", end: ")" },
  1844. alternatormarker: "|",
  1845. escapeChar: "\\",
  1846. mask: null,
  1847. oncomplete: $.noop, //executes when the mask is complete
  1848. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1849. oncleared: $.noop, //executes when the mask is cleared
  1850. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1851. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1852. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1853. removeMaskOnSubmit: false, //remove the mask before submitting the form.
  1854. clearMaskOnLostFocus: true,
  1855. insertMode: true, //insert the input or overwrite the input
  1856. clearIncomplete: false, //clear the incomplete input on blur
  1857. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1858. alias: null,
  1859. onKeyUp: $.noop, //callback to implement autocomplete on certain keys for example
  1860. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1861. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1862. onBeforeWrite: undefined, //executes before writing to the masked element. args => event, opts
  1863. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1864. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1865. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1866. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1867. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1868. showTooltip: false, //show the activemask as tooltip
  1869. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1870. rightAlign: false, //align to the right
  1871. undoOnEscape: true, //pressing escape reverts the value to the value before focus
  1872. //numeric basic properties
  1873. radixPoint: "", //".", // | ","
  1874. radixFocus: false, //position caret to radixpoint on initial click
  1875. //numeric basic properties
  1876. nojumps: false, //do not jump over fixed parts in the mask
  1877. nojumpsThreshold: 0, //start nojumps as of
  1878. 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
  1879. definitions: {
  1880. '9': {
  1881. validator: "[0-9]",
  1882. cardinality: 1,
  1883. definitionSymbol: "*"
  1884. },
  1885. 'a': {
  1886. validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  1887. cardinality: 1,
  1888. definitionSymbol: "*"
  1889. },
  1890. '*': {
  1891. validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  1892. cardinality: 1
  1893. }
  1894. },
  1895. //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1896. 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],
  1897. isComplete: undefined //override for isComplete - args => buffer, opts - return true || false
  1898. },
  1899. keyCode: {
  1900. 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,
  1901. 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
  1902. },
  1903. masksCache: {},
  1904. escapeRegex: function (str) {
  1905. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1906. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1907. },
  1908. format: function (value, options, metadata) {
  1909. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1910. resolveAlias(opts.alias, options, opts);
  1911. return maskScope({ "action": "format", "value": value, "metadata": metadata }, generateMaskSet(opts), opts);
  1912. },
  1913. isValid: function (value, options) {
  1914. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1915. resolveAlias(opts.alias, options, opts);
  1916. return maskScope({ "action": "isValid", "value": value }, generateMaskSet(opts), opts);
  1917. }
  1918. };
  1919. $.fn.inputmask = function (fn, options, targetScope, targetData, msk) {
  1920. targetScope = targetScope || maskScope;
  1921. targetData = targetData || "_inputmask";
  1922. function importAttributeOptions(npt, opts, importedOptionsContainer) {
  1923. var $npt = $(npt);
  1924. if ($npt.data("inputmask-alias")) {
  1925. resolveAlias($npt.data("inputmask-alias"), {}, opts);
  1926. }
  1927. for (var option in opts) {
  1928. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  1929. if (optionData != undefined) {
  1930. if (option == "mask" && optionData.indexOf("[") == 0) {
  1931. opts[option] = optionData.replace(/[\s[\]]/g, "").split("','");
  1932. opts[option][0] = opts[option][0].replace("'", "");
  1933. opts[option][opts[option].length - 1] = opts[option][opts[option].length - 1].replace("'", "");
  1934. } else
  1935. opts[option] = typeof optionData == "boolean" ? optionData : optionData.toString();
  1936. if (importedOptionsContainer)
  1937. importedOptionsContainer[option] = opts[option];
  1938. }
  1939. }
  1940. return opts;
  1941. }
  1942. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1943. maskset;
  1944. if (typeof fn === "string") {
  1945. switch (fn) {
  1946. case "mask":
  1947. //resolve possible aliases given by options
  1948. resolveAlias(opts.alias, options, opts);
  1949. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1950. if (maskset == undefined) { return this; }
  1951. return this.each(function () {
  1952. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1953. });
  1954. case "unmaskedvalue":
  1955. var $input = $(this);
  1956. if ($input.data(targetData)) {
  1957. return targetScope({ "action": "unmaskedvalue", "$input": $input });
  1958. } else return $input.val();
  1959. case "remove":
  1960. return this.each(function () {
  1961. var $input = $(this);
  1962. if ($input.data(targetData)) {
  1963. targetScope({ "action": "remove", "el": this });
  1964. }
  1965. });
  1966. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1967. if (this.data(targetData)) {
  1968. return targetScope({ "action": "getemptymask", "el": this });
  1969. }
  1970. else return "";
  1971. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1972. return this.data(targetData) ? !this.data(targetData)['opts'].autoUnmask : false;
  1973. case "isComplete":
  1974. if (this.data(targetData)) {
  1975. return targetScope({ "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
  1976. } else return true;
  1977. case "getmetadata": //return mask metadata if exists
  1978. if (this.data(targetData)) {
  1979. return targetScope({ "action": "getmetadata", "el": this });
  1980. }
  1981. else return undefined;
  1982. case "_detectScope":
  1983. resolveAlias(opts.alias, options, opts);
  1984. if (msk != undefined && !resolveAlias(msk, options, opts) && $.inArray(msk, ["mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope"]) == -1) {
  1985. opts.mask = msk;
  1986. }
  1987. if ($.isFunction(opts.mask)) {
  1988. opts.mask = opts.mask.call(this, opts);
  1989. }
  1990. return $.isArray(opts.mask);
  1991. default:
  1992. resolveAlias(opts.alias, options, opts);
  1993. //check if the fn is an alias
  1994. if (!resolveAlias(fn, options, opts)) {
  1995. //maybe fn is a mask so we try
  1996. //set mask
  1997. opts.mask = fn;
  1998. }
  1999. maskset = generateMaskSet(opts, targetScope !== maskScope);
  2000. if (maskset == undefined) { return this; }
  2001. return this.each(function () {
  2002. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  2003. });
  2004. }
  2005. } else if (typeof fn == "object") {
  2006. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  2007. resolveAlias(opts.alias, fn, opts); //resolve aliases
  2008. maskset = generateMaskSet(opts, targetScope !== maskScope);
  2009. if (maskset == undefined) { return this; }
  2010. return this.each(function () {
  2011. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  2012. });
  2013. } else if (fn == undefined) {
  2014. //look for data-inputmask atribute - the attribute should only contain optipns
  2015. return this.each(function () {
  2016. var attrOptions = $(this).attr("data-inputmask");
  2017. if (attrOptions && attrOptions != "") {
  2018. try {
  2019. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  2020. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  2021. $.extend(true, dataoptions, options);
  2022. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  2023. opts = importAttributeOptions(this, opts);
  2024. resolveAlias(opts.alias, dataoptions, opts);
  2025. opts.alias = undefined;
  2026. $(this).inputmask("mask", opts, targetScope);
  2027. } catch (ex) { } //need a more relax parseJSON
  2028. }
  2029. if ($(this).attr("data-inputmask-mask") || $(this).attr("data-inputmask-alias")) {
  2030. opts = $.extend(true, {}, $.inputmask.defaults, {});
  2031. var dataOptions = {};
  2032. opts = importAttributeOptions(this, opts, dataOptions);
  2033. resolveAlias(opts.alias, dataOptions, opts);
  2034. opts.alias = undefined;
  2035. $(this).inputmask("mask", opts, targetScope);
  2036. }
  2037. });
  2038. }
  2039. };
  2040. }
  2041. return $.fn.inputmask;
  2042. })(jQuery);