jquery.inputmask.js 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. /**
  2. * @license 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. eventName = 'on' + eventName,
  14. isSupported = (eventName in el);
  15. if (!isSupported) {
  16. el.setAttribute(eventName, 'return;');
  17. isSupported = typeof el[eventName] == 'function';
  18. }
  19. el = null;
  20. return isSupported;
  21. }
  22. function resolveAlias(aliasStr, options, opts) {
  23. var aliasDefinition = opts.aliases[aliasStr];
  24. if (aliasDefinition) {
  25. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  26. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  27. $.extend(true, opts, options); //reapply extra given options
  28. return true;
  29. }
  30. return false;
  31. }
  32. function generateMaskSet(opts) {
  33. var ms = [];
  34. function analyseMask(mask) {
  35. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  36. escaped = false;
  37. function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  38. this.matches = [];
  39. this.isGroup = isGroup || false;
  40. this.isOptional = isOptional || false;
  41. this.isQuantifier = isQuantifier || false;
  42. this.isAlternator = isAlternator || false;
  43. this.quantifier = { min: 1, max: 1 };
  44. };
  45. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder}
  46. function insertTestDefinition(mtoken, element, position) {
  47. var maskdef = opts.definitions[element];
  48. var newBlockMarker = mtoken.matches.length == 0;
  49. position = position != undefined ? position : mtoken.matches.length;
  50. if (maskdef && !escaped) {
  51. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  52. for (var i = 1; i < maskdef.cardinality; i++) {
  53. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  54. 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"] });
  55. }
  56. 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"] });
  57. } else {
  58. mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element, placeholder: undefined });
  59. escaped = false;
  60. }
  61. }
  62. var currentToken = new maskToken(),
  63. match,
  64. m,
  65. openenings = [],
  66. maskTokens = [];
  67. while (match = tokenizer.exec(mask)) {
  68. m = match[0];
  69. switch (m.charAt(0)) {
  70. case opts.optionalmarker.end:
  71. // optional closing
  72. case opts.groupmarker.end:
  73. // Group closing
  74. var openingToken = openenings.pop();
  75. if (openenings.length > 0) {
  76. openenings[openenings.length - 1]["matches"].push(openingToken);
  77. } else {
  78. currentToken.matches.push(openingToken);
  79. }
  80. break;
  81. case opts.optionalmarker.start:
  82. // optional opening
  83. openenings.push(new maskToken(false, true));
  84. break;
  85. case opts.groupmarker.start:
  86. // Group opening
  87. openenings.push(new maskToken(true));
  88. break;
  89. case opts.quantifiermarker.start:
  90. //Quantifier
  91. var quantifier = new maskToken(false, false, true);
  92. m = m.replace(/[{}]/g, "");
  93. var mq = m.split(","),
  94. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  95. mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  96. if (mq1 == "*" || mq1 == "+") {
  97. mq0 = mq1 == "*" ? 0 : 1;
  98. }
  99. quantifier.quantifier = { min: mq0, max: mq1 };
  100. if (openenings.length > 0) {
  101. var matches = openenings[openenings.length - 1]["matches"];
  102. var match = matches.pop();
  103. if (!match["isGroup"]) {
  104. var groupToken = new maskToken(true);
  105. groupToken.matches.push(match);
  106. match = groupToken;
  107. }
  108. matches.push(match);
  109. matches.push(quantifier);
  110. } else {
  111. var match = currentToken.matches.pop();
  112. if (!match["isGroup"]) {
  113. var groupToken = new maskToken(true);
  114. groupToken.matches.push(match);
  115. match = groupToken;
  116. }
  117. currentToken.matches.push(match);
  118. currentToken.matches.push(quantifier);
  119. }
  120. break;
  121. case opts.escapeChar:
  122. escaped = true;
  123. break;
  124. case opts.alternatormarker:
  125. break;
  126. default:
  127. if (openenings.length > 0) {
  128. insertTestDefinition(openenings[openenings.length - 1], m);
  129. } else {
  130. if (currentToken.matches.length > 0) {
  131. var lastMatch = currentToken.matches[currentToken.matches.length - 1];
  132. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  133. lastMatch.isGroup = false;
  134. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  135. insertTestDefinition(lastMatch, opts.groupmarker.end);
  136. }
  137. }
  138. insertTestDefinition(currentToken, m);
  139. }
  140. }
  141. }
  142. if (currentToken.matches.length > 0) {
  143. var lastMatch = currentToken.matches[currentToken.matches.length - 1];
  144. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  145. lastMatch.isGroup = false;
  146. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  147. insertTestDefinition(lastMatch, opts.groupmarker.end);
  148. }
  149. maskTokens.push(currentToken);
  150. }
  151. //console.log(JSON.stringify(maskTokens));
  152. return maskTokens;
  153. }
  154. function generateMask(mask, metadata) {
  155. if (opts.numericInput && opts.multi !== true) { //TODO FIX FOR DYNAMIC MASKS WITH QUANTIFIERS
  156. mask = mask.split('').reverse();
  157. for (var ndx = 0; ndx < mask.length; ndx++) {
  158. if (mask[ndx] == opts.optionalmarker.start)
  159. mask[ndx] = opts.optionalmarker.end;
  160. else if (mask[ndx] == opts.optionalmarker.end)
  161. mask[ndx] = opts.optionalmarker.start;
  162. else if (mask[ndx] == opts.groupmarker.start)
  163. mask[ndx] = opts.groupmarker.end;
  164. else if (mask[ndx] == opts.groupmarker.end)
  165. mask[ndx] = opts.groupmarker.start;
  166. }
  167. mask = mask.join('');
  168. }
  169. if (mask == undefined || mask == "")
  170. return undefined;
  171. else {
  172. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  173. var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
  174. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  175. }
  176. if ($.inputmask.masksCache[mask] == undefined) {
  177. $.inputmask.masksCache[mask] = {
  178. "mask": mask,
  179. "maskToken": analyseMask(mask),
  180. "validPositions": {},
  181. "_buffer": undefined,
  182. "buffer": undefined,
  183. "tests": {},
  184. "metadata": metadata
  185. };
  186. }
  187. return $.extend(true, {}, $.inputmask.masksCache[mask]);
  188. }
  189. }
  190. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  191. opts.mask = opts.mask.call(this, opts);
  192. }
  193. if ($.isArray(opts.mask)) {
  194. $.each(opts.mask, function (ndx, msk) {
  195. if (msk["mask"] != undefined) {
  196. ms.push(generateMask(msk["mask"].toString(), msk));
  197. } else {
  198. ms.push(generateMask(msk.toString()));
  199. }
  200. });
  201. } else {
  202. if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  203. opts.placeholder = "";
  204. } //hide placeholder with single non-greedy mask
  205. if (opts.mask["mask"] != undefined) {
  206. ms = generateMask(opts.mask["mask"].toString(), opts.mask);
  207. } else {
  208. ms = generateMask(opts.mask.toString());
  209. }
  210. }
  211. return ms;
  212. }
  213. var msie1x = typeof ScriptEngineMajorVersion === "function"
  214. ? ScriptEngineMajorVersion() //IE11 detection
  215. : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
  216. ua = navigator.userAgent,
  217. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  218. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  219. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  220. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  221. 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),
  222. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  223. //if (androidchrome) {
  224. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  225. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  226. // androidchrome32 = (version == 32);
  227. //}
  228. //masking scope
  229. //actionObj definition see below
  230. function maskScope(actionObj, maskset, opts) {
  231. var isRTL = false,
  232. valueOnFocus,
  233. $el,
  234. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  235. skipInputEvent = false, //skip when triggered from within inputmask
  236. ignorable = false,
  237. maxLength;
  238. //maskset helperfunctions
  239. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  240. minimalPos = minimalPos || 0;
  241. var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos;
  242. do {
  243. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  244. var validPos = getMaskSet()['validPositions'][pos];
  245. test = validPos["match"];
  246. ndxIntlzr = validPos["locator"].slice();
  247. maskTemplate.push(test["fn"] == null ? test["def"] : (includeInput === true ? validPos["input"] : test["placeholder"] || opts.placeholder.charAt(pos % opts.placeholder.length)));
  248. } else {
  249. if (minimalPos > pos) {
  250. var testPositions = getTests(pos, ndxIntlzr, pos - 1);
  251. testPos = testPositions[0];
  252. } else {
  253. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  254. }
  255. test = testPos["match"];
  256. ndxIntlzr = testPos["locator"].slice();
  257. maskTemplate.push(test["fn"] == null ? test["def"] : test["placeholder"] || opts.placeholder.charAt(pos % opts.placeholder.length));
  258. }
  259. pos++;
  260. } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  261. maskTemplate.pop(); //drop the last one which is empty
  262. return maskTemplate;
  263. }
  264. function getMaskSet() {
  265. return maskset;
  266. }
  267. function resetMaskSet(soft) {
  268. var maskset = getMaskSet();
  269. maskset["buffer"] = undefined;
  270. maskset["tests"] = {};
  271. if (soft !== true) {
  272. maskset["_buffer"] = undefined;
  273. maskset["validPositions"] = {};
  274. maskset["p"] = -1;
  275. }
  276. }
  277. function getLastValidPosition(closestTo) {
  278. var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset["validPositions"];
  279. if (closestTo == undefined) closestTo = -1;
  280. var before = lastValidPosition, after = lastValidPosition;
  281. for (var posNdx in valids) {
  282. var psNdx = parseInt(posNdx);
  283. if (closestTo == -1 || valids[psNdx]["match"].fn != null) {
  284. if (psNdx < closestTo) before = psNdx;
  285. if (psNdx >= closestTo) after = psNdx;
  286. }
  287. }
  288. lastValidPosition = (closestTo - before) > 1 || after < closestTo ? before : after;
  289. return lastValidPosition;
  290. }
  291. function setValidPosition(pos, validTest, fromSetValid) {
  292. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  293. //reposition & revalidate others
  294. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]), lvp = getLastValidPosition(), i;
  295. for (i = pos; i <= lvp; i++) { //clear selection
  296. delete getMaskSet()["validPositions"][i];
  297. }
  298. getMaskSet()["validPositions"][pos] = validTest;
  299. var valid = true;
  300. for (i = pos; i <= lvp ; i++) {
  301. var t = positionsClone[i];
  302. if (t != undefined) {
  303. var j = t["match"].fn == null ? i + 1 : seekNext(i);
  304. if (positionCanMatchDefinition(j, t["match"].def)) {
  305. valid = valid && isValid(j, t["input"], true, true) !== false;
  306. } else valid = false;
  307. }
  308. if (!valid) break;
  309. }
  310. if (!valid) {
  311. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  312. return false;
  313. }
  314. } else
  315. getMaskSet()["validPositions"][pos] = validTest;
  316. return true;
  317. }
  318. function stripValidPositions(start, end) {
  319. var i, startPos = start, lvp;
  320. for (i = start; i < end; i++) { //clear selection
  321. //TODO FIXME BETTER CHECK
  322. delete getMaskSet()["validPositions"][i];
  323. }
  324. for (i = end ; i <= getLastValidPosition() ;) {
  325. var t = getMaskSet()["validPositions"][i];
  326. var s = getMaskSet()["validPositions"][startPos];
  327. if (t != undefined && s == undefined) {
  328. if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) {
  329. delete getMaskSet()["validPositions"][i];
  330. i++;
  331. }
  332. startPos++;
  333. } else i++;
  334. }
  335. lvp = getLastValidPosition();
  336. //catchup
  337. while (lvp > 0 && (getMaskSet()["validPositions"][lvp] == undefined || getMaskSet()["validPositions"][lvp].match.fn == null)) {
  338. delete getMaskSet()["validPositions"][lvp];
  339. lvp--;
  340. }
  341. resetMaskSet(true);
  342. }
  343. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  344. var testPositions = getTests(pos, ndxIntlzr, tstPs), testPos;
  345. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  346. testPos = testPositions[ndx];
  347. if (opts.greedy || (testPos["match"] && (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true)) {
  348. break;
  349. }
  350. }
  351. return testPos;
  352. }
  353. function getTest(pos) {
  354. if (getMaskSet()['validPositions'][pos]) {
  355. return getMaskSet()['validPositions'][pos]["match"];
  356. }
  357. return getTests(pos)[0]["match"];
  358. }
  359. function positionCanMatchDefinition(pos, def) {
  360. var valid = false, tests = getTests(pos);
  361. for (var tndx = 0; tndx < tests.length; tndx++) {
  362. if (tests[tndx]["match"] && tests[tndx]["match"].def == def) {
  363. valid = true;
  364. break;
  365. }
  366. }
  367. return valid;
  368. };
  369. function getTests(pos, ndxIntlzr, tstPs) {
  370. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  371. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  372. function handleMatch(match, loopNdx, quantifierRecurse) {
  373. if (testPos == pos && match.matches == undefined) {
  374. matches.push({ "match": match, "locator": loopNdx.reverse() });
  375. return true;
  376. } else if (match.matches != undefined) {
  377. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  378. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  379. if (match) return true;
  380. } else if (match.isOptional) {
  381. var optionalToken = match;
  382. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  383. if (match) {
  384. var latestMatch = matches[matches.length - 1]["match"];
  385. var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
  386. if (isFirstMatch) {
  387. insertStop = true; //insert a stop for non greedy
  388. }
  389. testPos = pos; //match the position after the group
  390. }
  391. } else if (match.isAlternator) {
  392. //TODO
  393. } else if (match.isQuantifier && quantifierRecurse !== true) {
  394. var qt = match;
  395. opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!)
  396. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  397. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  398. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  399. if (match) {
  400. //get latest match
  401. var latestMatch = matches[matches.length - 1]["match"];
  402. latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1;
  403. var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
  404. if (isFirstMatch) { //search for next possible match
  405. if (qndx > qt.quantifier.min - 1) {
  406. insertStop = true;
  407. testPos = pos; //match the position after the group
  408. break; //stop quantifierloop
  409. } else return true;
  410. } else {
  411. return true;
  412. }
  413. }
  414. }
  415. } else {
  416. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  417. if (match)
  418. return true;
  419. }
  420. } else testPos++;
  421. }
  422. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  423. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  424. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  425. if (match && testPos == pos) {
  426. return match;
  427. } else if (testPos > pos) {
  428. break;
  429. }
  430. }
  431. }
  432. }
  433. //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  434. // return getMaskSet()['tests'][pos];
  435. //}
  436. if (ndxIntlzr == undefined) {
  437. var previousPos = pos - 1, test;
  438. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  439. previousPos--;
  440. }
  441. if (test != undefined && previousPos > -1) {
  442. testPos = previousPos;
  443. ndxInitializer = test["locator"].slice();
  444. } else {
  445. previousPos = pos - 1;
  446. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  447. previousPos--;
  448. }
  449. if (test != undefined && previousPos > -1) {
  450. testPos = previousPos;
  451. ndxInitializer = test[0]["locator"].slice();
  452. }
  453. }
  454. }
  455. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  456. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  457. if ((match && testPos == pos) || testPos > pos) {
  458. break;
  459. }
  460. }
  461. if (matches.length == 0 || insertStop)
  462. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  463. getMaskSet()['tests'][pos] = matches;
  464. //console.log(pos + " - " + JSON.stringify(matches));
  465. return matches;
  466. }
  467. function getBufferTemplate() {
  468. if (getMaskSet()['_buffer'] == undefined) {
  469. //generate template
  470. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  471. }
  472. return getMaskSet()['_buffer'];
  473. }
  474. function getBuffer() {
  475. if (getMaskSet()['buffer'] == undefined) {
  476. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  477. }
  478. return getMaskSet()['buffer'];
  479. }
  480. function refreshFromBuffer(start, end) {
  481. var buffer = getBuffer().slice(); //work on clone
  482. if (start === true) {
  483. resetMaskSet();
  484. start = 0;
  485. end = buffer.length;
  486. } else {
  487. for (var i = start; i < end; i++) {
  488. delete getMaskSet()["validPositions"][i];
  489. delete getMaskSet()["tests"][i];
  490. }
  491. }
  492. for (var i = start; i < end; i++) {
  493. if (buffer[i] != opts.skipOptionalPartCharacter) {
  494. isValid(i, buffer[i], true, true);
  495. }
  496. }
  497. }
  498. function casing(elem, test) {
  499. switch (test.casing) {
  500. case "upper":
  501. elem = elem.toUpperCase();
  502. break;
  503. case "lower":
  504. elem = elem.toLowerCase();
  505. break;
  506. }
  507. return elem;
  508. }
  509. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  510. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  511. function _isValid(position, c, strict, fromSetValid) {
  512. var rslt = false;
  513. $.each(getTests(position), function (ndx, tst) {
  514. var test = tst["match"];
  515. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  516. for (var i = test.cardinality; i > loopend; i--) {
  517. chrs += getBufferElement(position - (i - 1));
  518. }
  519. if (c) {
  520. chrs += c;
  521. }
  522. //return is false or a json object => { pos: ??, c: ??} or true
  523. rslt = test.fn != null ?
  524. test.fn.test(chrs, getMaskSet(), position, strict, opts)
  525. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  526. { c: test["def"], pos: position }
  527. : false;
  528. if (rslt !== false) {
  529. var elem = rslt.c != undefined ? rslt.c : c;
  530. elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
  531. var validatedPos = position;
  532. if (rslt["remove"] != undefined) { //remove position
  533. stripValidPositions(rslt["remove"], rslt["remove"] + 1);
  534. }
  535. if (rslt["refreshFromBuffer"]) {
  536. var refresh = rslt["refreshFromBuffer"];
  537. strict = true;
  538. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
  539. if (rslt.pos == undefined && rslt.c == undefined) {
  540. rslt.pos = getLastValidPosition();
  541. return false;//breakout if refreshFromBuffer && nothing to insert
  542. }
  543. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  544. if (validatedPos != position) {
  545. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  546. return false;
  547. }
  548. } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
  549. validatedPos = rslt["pos"];
  550. refreshFromBuffer(position, validatedPos);
  551. if (validatedPos != position) {
  552. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  553. return false;
  554. }
  555. }
  556. if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
  557. return false; //breakout if nothing to insert
  558. }
  559. if (ndx > 0) {
  560. resetMaskSet(true);
  561. }
  562. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid))
  563. rslt = false;
  564. return false; //break from $.each
  565. }
  566. });
  567. return rslt;
  568. }
  569. //Check for a nonmask before the pos
  570. var buffer = getBuffer();
  571. for (var pndx = pos - 1; pndx > -1; pndx--) {
  572. if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx].fn == null)
  573. break;
  574. else if ((!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) {
  575. _isValid(pndx, buffer[pndx], true);
  576. break;
  577. }
  578. }
  579. var maskPos = pos;
  580. if (maskPos >= getMaskLength()) return false;
  581. var result = _isValid(maskPos, c, strict, fromSetValid);
  582. if (!strict && result === false) {
  583. var currentPosValid = getMaskSet()["validPositions"][maskPos];
  584. if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
  585. result = { "caret": seekNext(maskPos) };
  586. } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
  587. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  588. result = _isValid(nPos, c, strict, fromSetValid);
  589. if (result !== false) {
  590. maskPos = nPos;
  591. break;
  592. }
  593. }
  594. }
  595. }
  596. if (result === true) result = { "pos": maskPos };
  597. return result;
  598. }
  599. function isMask(pos) {
  600. var test = getTest(pos);
  601. return test.fn != null ? test.fn : false;
  602. }
  603. function getMaskLength() {
  604. var maskLength;
  605. maxLength = $el.prop('maxLength');
  606. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  607. if (opts.greedy == false) {
  608. var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp],
  609. ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
  610. for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
  611. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  612. ndxIntlzr = testPos["locator"].slice();
  613. }
  614. maskLength = pos;
  615. } else
  616. maskLength = getBuffer().length;
  617. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  618. }
  619. function seekNext(pos) {
  620. var maskL = getMaskLength();
  621. if (pos >= maskL) return maskL;
  622. var position = pos;
  623. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
  624. }
  625. return position;
  626. }
  627. function seekPrevious(pos) {
  628. var position = pos;
  629. if (position <= 0) return 0;
  630. while (--position > 0 && !isMask(position)) {
  631. };
  632. return position;
  633. }
  634. function getBufferElement(position) {
  635. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  636. }
  637. function writeBuffer(input, buffer, caretPos) {
  638. input._valueSet(buffer.join(''));
  639. if (caretPos != undefined) {
  640. caret(input, caretPos);
  641. }
  642. }
  643. function getPlaceholder(pos, test) {
  644. test = test || getTest(pos);
  645. return test["placeholder"] || (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  646. }
  647. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  648. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  649. resetMaskSet();
  650. if (writeOut) input._valueSet(""); //initial clear
  651. $.each(inputValue, function (ndx, charCode) {
  652. if (intelliCheck === true) {
  653. var p = getMaskSet()["p"],
  654. lvp = p == -1 ? p : seekPrevious(p),
  655. pos = lvp == -1 ? ndx : seekNext(lvp);
  656. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
  657. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
  658. }
  659. } else {
  660. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
  661. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  662. }
  663. });
  664. if (writeOut)
  665. writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined);
  666. }
  667. function escapeRegex(str) {
  668. return $.inputmask.escapeRegex.call(this, str);
  669. }
  670. function truncateInput(inputValue) {
  671. return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
  672. }
  673. function unmaskedvalue($input, skipDatepickerCheck) {
  674. if ($input.data('_inputmask') && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  675. var umValue = [], vps = getMaskSet()["validPositions"];
  676. for (var pndx in vps) {
  677. if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
  678. umValue.push(vps[pndx]["input"]);
  679. }
  680. }
  681. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  682. var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
  683. if ($.isFunction(opts.onUnMask)) {
  684. unmaskedValue = opts.onUnMask.call($input, bufferValue, unmaskedValue, opts);
  685. }
  686. return unmaskedValue;
  687. } else {
  688. return $input[0]._valueGet();
  689. }
  690. }
  691. function TranslatePosition(pos) {
  692. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  693. var bffrLght = getBuffer().length;
  694. pos = bffrLght - pos;
  695. }
  696. return pos;
  697. }
  698. function caret(input, begin, end) {
  699. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  700. if (typeof begin == 'number') {
  701. begin = TranslatePosition(begin);
  702. end = TranslatePosition(end);
  703. end = (typeof end == 'number') ? end : begin;
  704. //store caret for multi scope
  705. var data = $(npt).data('_inputmask') || {};
  706. data["caret"] = { "begin": begin, "end": end };
  707. $(npt).data('_inputmask', data);
  708. if (!$(npt).is(":visible")) {
  709. return;
  710. }
  711. npt.scrollLeft = npt.scrollWidth;
  712. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  713. if (npt.setSelectionRange) {
  714. npt.selectionStart = begin;
  715. npt.selectionEnd = end;
  716. } else if (npt.createTextRange) {
  717. range = npt.createTextRange();
  718. range.collapse(true);
  719. range.moveEnd('character', end);
  720. range.moveStart('character', begin);
  721. range.select();
  722. }
  723. } else {
  724. var data = $(npt).data('_inputmask');
  725. if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
  726. begin = data["caret"]["begin"];
  727. end = data["caret"]["end"];
  728. } else if (npt.setSelectionRange) {
  729. begin = npt.selectionStart;
  730. end = npt.selectionEnd;
  731. } else if (document.selection && document.selection.createRange) {
  732. range = document.selection.createRange();
  733. begin = 0 - range.duplicate().moveStart('character', -100000);
  734. end = begin + range.text.length;
  735. }
  736. begin = TranslatePosition(begin);
  737. end = TranslatePosition(end);
  738. return { "begin": begin, "end": end };
  739. }
  740. }
  741. function determineLastRequiredPosition(returnDefinition) {
  742. var buffer = getBuffer(), bl = buffer.length,
  743. pos, lvp = getLastValidPosition(), positions = {},
  744. ndxIntlzr = getMaskSet()["validPositions"][lvp] != undefined ? getMaskSet()["validPositions"][lvp]["locator"].slice() : undefined, testPos;
  745. for (pos = lvp + 1; pos < buffer.length; pos++) {
  746. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  747. ndxIntlzr = testPos["locator"].slice();
  748. positions[pos] = $.extend(true, {}, testPos);
  749. }
  750. for (pos = bl - 1; pos > lvp; pos--) {
  751. testPos = positions[pos]["match"];
  752. if ((testPos.optionality || testPos.optionalQuantifier) && buffer[pos] == getPlaceholder(pos, testPos)) {
  753. bl--;
  754. } else break;
  755. }
  756. return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
  757. }
  758. function clearOptionalTail(input) {
  759. var buffer = getBuffer(), tmpBuffer = buffer.slice();
  760. var rl = determineLastRequiredPosition();
  761. tmpBuffer.length = rl;
  762. writeBuffer(input, tmpBuffer);
  763. }
  764. function isComplete(buffer) { //return true / false / undefined (repeat *)
  765. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  766. if (opts.repeat == "*") return undefined;
  767. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
  768. if (lvp == aml) {
  769. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
  770. complete = true;
  771. for (var i = 0; i <= aml; i++) {
  772. var mask = isMask(i);
  773. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  774. complete = false;
  775. break;
  776. }
  777. }
  778. }
  779. }
  780. return complete;
  781. }
  782. function isSelection(begin, end) {
  783. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  784. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  785. }
  786. function installEventRuler(npt) {
  787. var events = $._data(npt).events;
  788. $.each(events, function (eventType, eventHandlers) {
  789. $.each(eventHandlers, function (ndx, eventHandler) {
  790. if (eventHandler.namespace == "inputmask") {
  791. if (eventHandler.type != "setvalue") {
  792. var handler = eventHandler.handler;
  793. eventHandler.handler = function (e) {
  794. if (this.readOnly || this.disabled)
  795. e.preventDefault;
  796. else
  797. return handler.apply(this, arguments);
  798. };
  799. }
  800. }
  801. });
  802. });
  803. }
  804. function patchValueProperty(npt) {
  805. function PatchValhook(type) {
  806. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  807. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  808. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  809. elem.value = value;
  810. return elem;
  811. };
  812. $.valHooks[type] = {
  813. get: function (elem) {
  814. var $elem = $(elem);
  815. if ($elem.data('_inputmask')) {
  816. if ($elem.data('_inputmask')['opts'].autoUnmask)
  817. return $elem.inputmask('unmaskedvalue');
  818. else {
  819. var result = valueGet(elem),
  820. inputData = $elem.data('_inputmask'),
  821. maskset = inputData['maskset'],
  822. bufferTemplate = maskset['_buffer'];
  823. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  824. return result != bufferTemplate ? result : '';
  825. }
  826. } else return valueGet(elem);
  827. },
  828. set: function (elem, value) {
  829. var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
  830. if (inputData) {
  831. result = valueSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
  832. $elem.triggerHandler('setvalue.inputmask');
  833. } else {
  834. result = valueSet(elem, value);
  835. }
  836. return result;
  837. },
  838. inputmaskpatch: true
  839. };
  840. }
  841. }
  842. var valueProperty;
  843. if (Object.getOwnPropertyDescriptor)
  844. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  845. if (valueProperty && valueProperty.get) {
  846. if (!npt._valueGet) {
  847. var valueGet = valueProperty.get;
  848. var valueSet = valueProperty.set;
  849. npt._valueGet = function () {
  850. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  851. };
  852. npt._valueSet = function (value) {
  853. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  854. };
  855. Object.defineProperty(npt, "value", {
  856. get: function () {
  857. var $self = $(this), inputData = $(this).data('_inputmask');
  858. if (inputData) {
  859. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  860. } else return valueGet.call(this);
  861. },
  862. set: function (value) {
  863. var inputData = $(this).data('_inputmask');
  864. if (inputData) {
  865. valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
  866. $(this).triggerHandler('setvalue.inputmask');
  867. } else {
  868. valueSet.call(this, value);
  869. }
  870. }
  871. });
  872. }
  873. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  874. if (!npt._valueGet) {
  875. var valueGet = npt.__lookupGetter__("value");
  876. var valueSet = npt.__lookupSetter__("value");
  877. npt._valueGet = function () {
  878. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  879. };
  880. npt._valueSet = function (value) {
  881. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  882. };
  883. npt.__defineGetter__("value", function () {
  884. var $self = $(this), inputData = $(this).data('_inputmask');
  885. if (inputData) {
  886. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  887. } else return valueGet.call(this);
  888. });
  889. npt.__defineSetter__("value", function (value) {
  890. var inputData = $(this).data('_inputmask');
  891. if (inputData) {
  892. valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
  893. $(this).triggerHandler('setvalue.inputmask');
  894. } else {
  895. valueSet.call(this, value);
  896. }
  897. });
  898. }
  899. } else {
  900. if (!npt._valueGet) {
  901. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  902. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  903. }
  904. PatchValhook(npt.type);
  905. }
  906. }
  907. function handleRemove(input, k, pos) {
  908. if (opts.numericInput || isRTL) {
  909. if (k == opts.keyCode.BACKSPACE)
  910. k = opts.keyCode.DELETE;
  911. else if (k == opts.keyCode.DELETE)
  912. k = opts.keyCode.BACKSPACE;
  913. if (isRTL) {
  914. var pend = pos.end;
  915. pos.end = pos.begin;
  916. pos.begin = pend;
  917. }
  918. }
  919. if (k == opts.keyCode.BACKSPACE && pos.end - pos.begin <= 1)
  920. pos.begin = seekPrevious(pos.begin);
  921. else if (k == opts.keyCode.DELETE && pos.begin == pos.end)
  922. pos.end++;
  923. stripValidPositions(pos.begin, pos.end);
  924. var firstMaskedPos = getLastValidPosition(pos.begin);
  925. if (firstMaskedPos < pos.begin) {
  926. getMaskSet()["p"] = seekNext(firstMaskedPos);
  927. } else {
  928. getMaskSet()["p"] = pos.begin;
  929. }
  930. }
  931. function handleOnKeyResult(input, keyResult, caretPos) {
  932. if (keyResult && keyResult["refreshFromBuffer"]) {
  933. var refresh = keyResult["refreshFromBuffer"];
  934. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
  935. resetMaskSet(true);
  936. writeBuffer(input, getBuffer());
  937. caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
  938. }
  939. }
  940. function keydownEvent(e) {
  941. //Safari 5.1.x - modal dialog fires keypress twice workaround
  942. skipKeyPressEvent = false;
  943. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  944. //backspace, delete, and escape get special treatment
  945. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  946. e.preventDefault(); //stop default action but allow propagation
  947. if (k == 88) valueOnFocus = getBuffer().join('');
  948. handleRemove(input, k, pos);
  949. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  950. if (input._valueGet() == getBufferTemplate().join(''))
  951. $input.trigger('cleared');
  952. if (opts.showTooltip) { //update tooltip
  953. $input.prop("title", getMaskSet()["mask"]);
  954. }
  955. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  956. setTimeout(function () {
  957. var caretPos = seekNext(getLastValidPosition());
  958. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  959. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  960. }, 0);
  961. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  962. caret(input, 0, e.shiftKey ? pos.begin : 0);
  963. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  964. checkVal(input, true, false, valueOnFocus.split(''));
  965. $input.click();
  966. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  967. opts.insertMode = !opts.insertMode;
  968. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  969. } else if (opts.insertMode == false && !e.shiftKey) {
  970. if (k == opts.keyCode.RIGHT) {
  971. setTimeout(function () {
  972. var caretPos = caret(input);
  973. caret(input, caretPos.begin);
  974. }, 0);
  975. } else if (k == opts.keyCode.LEFT) {
  976. setTimeout(function () {
  977. var caretPos = caret(input);
  978. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  979. }, 0);
  980. }
  981. }
  982. var currentCaretPos = caret(input);
  983. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), opts);
  984. handleOnKeyResult(input, keydownResult, currentCaretPos);
  985. ignorable = $.inArray(k, opts.ignorables) != -1;
  986. }
  987. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  988. //Safari 5.1.x - modal dialog fires keypress twice workaround
  989. if (k == undefined && skipKeyPressEvent) return false;
  990. skipKeyPressEvent = true;
  991. var input = this, $input = $(input);
  992. e = e || window.event;
  993. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  994. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  995. return true;
  996. } else {
  997. if (k) {
  998. //special treat the decimal separator
  999. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1000. var pos, forwardPosition, c = String.fromCharCode(k);
  1001. if (checkval) {
  1002. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  1003. pos = { begin: pcaret, end: pcaret };
  1004. } else {
  1005. pos = caret(input);
  1006. }
  1007. //should we clear a possible selection??
  1008. var isSlctn = isSelection(pos.begin, pos.end);
  1009. if (isSlctn) {
  1010. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1011. handleRemove(input, opts.keyCode.DELETE, pos);
  1012. if (!opts.insertMode) { //preserve some space
  1013. opts.insertMode = !opts.insertMode;
  1014. setValidPosition(pos.begin, strict);
  1015. opts.insertMode = !opts.insertMode;
  1016. }
  1017. isSlctn = !opts.multi;
  1018. }
  1019. getMaskSet()["writeOutBuffer"] = true;
  1020. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1021. var valResult = isValid(p, c, strict);
  1022. if (valResult !== false) {
  1023. if (valResult !== true) {
  1024. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1025. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1026. }
  1027. resetMaskSet(true);
  1028. if (valResult.caret != undefined)
  1029. forwardPosition = valResult.caret;
  1030. else {
  1031. var vps = getMaskSet()["validPositions"];
  1032. if (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1)
  1033. forwardPosition = p + 1;
  1034. else
  1035. forwardPosition = seekNext(p);
  1036. }
  1037. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1038. }
  1039. if (writeOut !== false) {
  1040. var self = this;
  1041. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  1042. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1043. var buffer = getBuffer();
  1044. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1045. if (checkval !== true) {
  1046. setTimeout(function () { //timeout needed for IE
  1047. if (isComplete(buffer) === true)
  1048. $input.trigger("complete");
  1049. skipInputEvent = true;
  1050. $input.trigger("input");
  1051. }, 0);
  1052. }
  1053. } else if (isSlctn) {
  1054. getMaskSet()["buffer"] = undefined;
  1055. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1056. }
  1057. } else if (isSlctn) {
  1058. getMaskSet()["buffer"] = undefined;
  1059. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1060. }
  1061. if (opts.showTooltip) { //update tooltip
  1062. $input.prop("title", getMaskSet()["mask"]);
  1063. }
  1064. //needed for IE8 and below
  1065. if (e && checkval != true) {
  1066. e.preventDefault ? e.preventDefault() : e.returnValue = false;
  1067. var currentCaretPos = caret(input);
  1068. var keypressResult = opts.onKeyPress.call(this, e, getBuffer(), opts);
  1069. handleOnKeyResult(input, keypressResult, currentCaretPos);
  1070. }
  1071. var temp;
  1072. for (var i in getMaskSet().validPositions) {
  1073. temp += " " + i;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. function keyupEvent(e) {
  1079. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  1080. var currentCaretPos = caret(input);
  1081. var keyupResult = opts.onKeyUp.call(this, e, buffer, opts);
  1082. handleOnKeyResult(input, keyupResult, currentCaretPos);
  1083. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  1084. if ($input.hasClass('focus-inputmask') && input._valueGet().length == 0) {
  1085. resetMaskSet();
  1086. buffer = getBuffer();
  1087. writeBuffer(input, buffer);
  1088. caret(input, 0);
  1089. valueOnFocus = getBuffer().join('');
  1090. } else {
  1091. writeBuffer(input, buffer);
  1092. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  1093. }
  1094. }
  1095. }
  1096. function pasteEvent(e) {
  1097. if (skipInputEvent === true && e.type == "input") {
  1098. skipInputEvent = false;
  1099. return true;
  1100. }
  1101. var input = this, $input = $(input), inputValue = input._valueGet();
  1102. //paste event for IE8 and lower I guess ;-)
  1103. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1104. return true;
  1105. } else if (e.type == "paste") {
  1106. if (window.clipboardData && window.clipboardData.getData) { // IE
  1107. inputValue = window.clipboardData.getData('Text');
  1108. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  1109. inputValue = e.originalEvent.clipboardData.getData('text/plain');
  1110. }
  1111. }
  1112. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, inputValue, opts) : inputValue;
  1113. checkVal(input, true, false, pasteValue.split(''), true);
  1114. $input.click();
  1115. if (isComplete(getBuffer()) === true)
  1116. $input.trigger("complete");
  1117. return false;
  1118. }
  1119. function mobileInputEvent(e) {
  1120. if (skipInputEvent === true && e.type == "input") {
  1121. skipInputEvent = false;
  1122. return true;
  1123. }
  1124. var input = this;
  1125. //backspace in chrome32 only fires input event - detect & treat
  1126. var caretPos = caret(input),
  1127. currentValue = input._valueGet();
  1128. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1129. //correct caretposition for chrome
  1130. if (caretPos.begin > currentValue.length) {
  1131. caret(input, currentValue.length);
  1132. caretPos = caret(input);
  1133. }
  1134. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1135. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1136. && !isMask(caretPos.begin)) {
  1137. e.keyCode = opts.keyCode.BACKSPACE;
  1138. keydownEvent.call(input, e);
  1139. }
  1140. e.preventDefault();
  1141. }
  1142. function mask(el) {
  1143. $el = $(el);
  1144. if ($el.is(":input") && $el.attr("type") != "number") {
  1145. //store tests & original buffer in the input element - used to get the unmasked value
  1146. $el.data('_inputmask', {
  1147. 'maskset': maskset,
  1148. 'opts': opts,
  1149. 'isRTL': false
  1150. });
  1151. //show tooltip
  1152. if (opts.showTooltip) {
  1153. $el.prop("title", getMaskSet()["mask"]);
  1154. }
  1155. patchValueProperty(el);
  1156. if (el.dir == "rtl" || opts.rightAlign)
  1157. $el.css("text-align", "right");
  1158. if (el.dir == "rtl" || opts.numericInput) {
  1159. el.dir = "ltr";
  1160. $el.removeAttr("dir");
  1161. var inputData = $el.data('_inputmask');
  1162. inputData['isRTL'] = true;
  1163. $el.data('_inputmask', inputData);
  1164. isRTL = true;
  1165. }
  1166. //unbind all events - to make sure that no other mask will interfere when re-masking
  1167. $el.unbind(".inputmask");
  1168. $el.removeClass('focus-inputmask');
  1169. //bind events
  1170. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1171. if (valueOnFocus != getBuffer().join('')) {
  1172. $el.change();
  1173. }
  1174. }).bind('reset', function () {
  1175. setTimeout(function () {
  1176. $el.trigger("setvalue");
  1177. }, 0);
  1178. });
  1179. $el.bind("mouseenter.inputmask", function () {
  1180. var $input = $(this), input = this;
  1181. if (!$input.hasClass('focus-inputmask') && opts.showMaskOnHover) {
  1182. if (input._valueGet() != getBuffer().join('')) {
  1183. writeBuffer(input, getBuffer());
  1184. }
  1185. }
  1186. }).bind("blur.inputmask", function () {
  1187. var $input = $(this), input = this;
  1188. if ($input.data('_inputmask')) {
  1189. var nptValue = input._valueGet(), buffer = getBuffer();
  1190. $input.removeClass('focus-inputmask');
  1191. if (valueOnFocus != getBuffer().join('')) {
  1192. $input.change();
  1193. }
  1194. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1195. if (nptValue == getBufferTemplate().join(''))
  1196. input._valueSet('');
  1197. else { //clearout optional tail of the mask
  1198. clearOptionalTail(input);
  1199. }
  1200. }
  1201. if (isComplete(buffer) === false) {
  1202. $input.trigger("incomplete");
  1203. if (opts.clearIncomplete) {
  1204. resetMaskSet();
  1205. if (opts.clearMaskOnLostFocus)
  1206. input._valueSet('');
  1207. else {
  1208. buffer = getBufferTemplate().slice();
  1209. writeBuffer(input, buffer);
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }).bind("focus.inputmask", function () {
  1215. var $input = $(this), input = this, nptValue = input._valueGet();
  1216. if (opts.showMaskOnFocus && !$input.hasClass('focus-inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1217. if (input._valueGet() != getBuffer().join('')) {
  1218. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1219. }
  1220. }
  1221. $input.addClass('focus-inputmask');
  1222. valueOnFocus = getBuffer().join('');
  1223. }).bind("mouseleave.inputmask", function () {
  1224. var $input = $(this), input = this;
  1225. if (opts.clearMaskOnLostFocus) {
  1226. if (!$input.hasClass('focus-inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1227. if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
  1228. input._valueSet('');
  1229. else { //clearout optional tail of the mask
  1230. clearOptionalTail(input);
  1231. }
  1232. }
  1233. }
  1234. }).bind("click.inputmask", function () {
  1235. var input = this;
  1236. if ($(input).is(":focus")) {
  1237. setTimeout(function () {
  1238. var selectedCaret = caret(input);
  1239. if (selectedCaret.begin == selectedCaret.end) {
  1240. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1241. lvp = getLastValidPosition(clickPosition),
  1242. lastPosition = seekNext(lvp);
  1243. if (clickPosition < lastPosition) {
  1244. if (isMask(clickPosition))
  1245. caret(input, clickPosition);
  1246. else caret(input, seekNext(clickPosition));
  1247. } else
  1248. caret(input, lastPosition);
  1249. }
  1250. }, 0);
  1251. }
  1252. }).bind('dblclick.inputmask', function () {
  1253. var input = this;
  1254. setTimeout(function () {
  1255. caret(input, 0, seekNext(getLastValidPosition()));
  1256. }, 0);
  1257. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1258. ).bind('setvalue.inputmask', function () {
  1259. var input = this;
  1260. checkVal(input, true);
  1261. valueOnFocus = getBuffer().join('');
  1262. if (input._valueGet() == getBufferTemplate().join(''))
  1263. input._valueSet('');
  1264. }).bind('complete.inputmask', opts.oncomplete
  1265. ).bind('incomplete.inputmask', opts.onincomplete
  1266. ).bind('cleared.inputmask', opts.oncleared);
  1267. $el.bind("keydown.inputmask", keydownEvent
  1268. ).bind("keypress.inputmask", keypressEvent
  1269. ).bind("keyup.inputmask", keyupEvent);
  1270. if (android || androidfirefox || androidchrome || kindle) {
  1271. if (PasteEventType == "input") {
  1272. $el.unbind(PasteEventType + ".inputmask");
  1273. }
  1274. $el.bind("input.inputmask", mobileInputEvent);
  1275. }
  1276. if (msie1x)
  1277. $el.bind("input.inputmask", pasteEvent);
  1278. //apply mask
  1279. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1280. checkVal(el, true, false, initialValue.split(''), true);
  1281. valueOnFocus = getBuffer().join('');
  1282. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1283. var activeElement;
  1284. try {
  1285. activeElement = document.activeElement;
  1286. } catch (e) {
  1287. }
  1288. if (activeElement === el) { //position the caret when in focus
  1289. $el.addClass('focus-inputmask');
  1290. caret(el, seekNext(getLastValidPosition()));
  1291. } else {
  1292. if (isComplete(getBuffer()) === false) {
  1293. if (opts.clearIncomplete)
  1294. resetMaskSet();
  1295. }
  1296. if (opts.clearMaskOnLostFocus) {
  1297. if (getBuffer().join('') == getBufferTemplate().join('')) {
  1298. el._valueSet('');
  1299. } else {
  1300. clearOptionalTail(el);
  1301. }
  1302. } else {
  1303. writeBuffer(el, getBuffer());
  1304. }
  1305. }
  1306. installEventRuler(el);
  1307. }
  1308. }
  1309. //action object
  1310. if (actionObj != undefined) {
  1311. switch (actionObj["action"]) {
  1312. case "isComplete":
  1313. $el = $(actionObj["el"]);
  1314. maskset = $el.data('_inputmask')['maskset'];
  1315. opts = $el.data('_inputmask')['opts'];
  1316. return isComplete(actionObj["buffer"]);
  1317. case "unmaskedvalue":
  1318. $el = actionObj["$input"];
  1319. maskset = $el.data('_inputmask')['maskset'];
  1320. opts = $el.data('_inputmask')['opts'];
  1321. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1322. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1323. case "mask":
  1324. valueOnFocus = getBuffer().join('');
  1325. mask(actionObj["el"]);
  1326. break;
  1327. case "format":
  1328. $el = $({});
  1329. $el.data('_inputmask', {
  1330. 'maskset': maskset,
  1331. 'opts': opts,
  1332. 'isRTL': opts.numericInput
  1333. });
  1334. if (opts.numericInput) {
  1335. isRTL = true;
  1336. }
  1337. var valueBuffer = actionObj["value"].split('');
  1338. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer, true);
  1339. return isRTL ? getBuffer().reverse().join('') : getBuffer().join('');
  1340. case "isValid":
  1341. $el = $({});
  1342. $el.data('_inputmask', {
  1343. 'maskset': maskset,
  1344. 'opts': opts,
  1345. 'isRTL': opts.numericInput
  1346. });
  1347. if (opts.numericInput) {
  1348. isRTL = true;
  1349. }
  1350. var valueBuffer = actionObj["value"].split('');
  1351. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1352. var buffer = getBuffer();
  1353. var rl = determineLastRequiredPosition();
  1354. buffer.length = rl;
  1355. return isComplete(buffer) && actionObj["value"] == buffer.join('');
  1356. case "getemptymask":
  1357. $el = $(actionObj["el"]);
  1358. maskset = $el.data('_inputmask')['maskset'];
  1359. opts = $el.data('_inputmask')['opts'];
  1360. return getBufferTemplate();
  1361. case "remove":
  1362. var el = actionObj["el"];
  1363. $el = $(el);
  1364. maskset = $el.data('_inputmask')['maskset'];
  1365. opts = $el.data('_inputmask')['opts'];
  1366. //writeout the unmaskedvalue
  1367. el._valueSet(unmaskedvalue($el));
  1368. //unbind all events
  1369. $el.unbind(".inputmask");
  1370. $el.removeClass('focus-inputmask');
  1371. //clear data
  1372. $el.removeData('_inputmask');
  1373. //restore the value property
  1374. var valueProperty;
  1375. if (Object.getOwnPropertyDescriptor)
  1376. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  1377. if (valueProperty && valueProperty.get) {
  1378. if (el._valueGet) {
  1379. Object.defineProperty(el, "value", {
  1380. get: el._valueGet,
  1381. set: el._valueSet
  1382. });
  1383. }
  1384. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  1385. if (el._valueGet) {
  1386. el.__defineGetter__("value", el._valueGet);
  1387. el.__defineSetter__("value", el._valueSet);
  1388. }
  1389. }
  1390. try { //try catch needed for IE7 as it does not supports deleting fns
  1391. delete el._valueGet;
  1392. delete el._valueSet;
  1393. } catch (e) {
  1394. el._valueGet = undefined;
  1395. el._valueSet = undefined;
  1396. }
  1397. break;
  1398. }
  1399. }
  1400. };
  1401. $.inputmask = {
  1402. //options default
  1403. defaults: {
  1404. placeholder: "_",
  1405. optionalmarker: { start: "[", end: "]" },
  1406. quantifiermarker: { start: "{", end: "}" },
  1407. groupmarker: { start: "(", end: ")" },
  1408. alternatormarker: "|",
  1409. escapeChar: "\\",
  1410. mask: null,
  1411. oncomplete: $.noop, //executes when the mask is complete
  1412. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1413. oncleared: $.noop, //executes when the mask is cleared
  1414. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1415. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1416. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1417. clearMaskOnLostFocus: true,
  1418. insertMode: true, //insert the input or overwrite the input
  1419. clearIncomplete: false, //clear the incomplete input on blur
  1420. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1421. alias: null,
  1422. onKeyUp: $.noop, //callback to implement autocomplete on certain keys for example
  1423. onKeyPress: $.noop, //callback to implement autocomplete on certain keys for example
  1424. onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example
  1425. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1426. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1427. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1428. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1429. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1430. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1431. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1432. showTooltip: false, //show the activemask as tooltip
  1433. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1434. rightAlign: false, //align to the right
  1435. //numeric basic properties
  1436. radixPoint: "", //".", // | ","
  1437. //numeric basic properties
  1438. nojumps: false, //do not jump over fixed parts in the mask
  1439. nojumpsThreshold: 0, //start nojumps as of
  1440. definitions: {
  1441. '9': {
  1442. validator: "[0-9]",
  1443. cardinality: 1,
  1444. definitionSymbol: "*"
  1445. },
  1446. 'a': {
  1447. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1448. cardinality: 1,
  1449. definitionSymbol: "*"
  1450. },
  1451. '*': {
  1452. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1453. cardinality: 1
  1454. }
  1455. },
  1456. keyCode: {
  1457. 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,
  1458. 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
  1459. },
  1460. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1461. 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],
  1462. isComplete: undefined //override for isComplete - args => buffer, opts - return true || false
  1463. },
  1464. masksCache: {},
  1465. escapeRegex: function (str) {
  1466. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1467. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1468. },
  1469. format: function (value, options) {
  1470. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1471. resolveAlias(opts.alias, options, opts);
  1472. return maskScope({ "action": "format", "value": value }, generateMaskSet(opts), opts);
  1473. },
  1474. isValid: function (value, options) {
  1475. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1476. resolveAlias(opts.alias, options, opts);
  1477. return maskScope({ "action": "isValid", "value": value }, generateMaskSet(opts), opts);
  1478. }
  1479. };
  1480. $.fn.inputmask = function (fn, options, targetScope, targetData, msk) {
  1481. targetScope = targetScope || maskScope;
  1482. targetData = targetData || "_inputmask";
  1483. function importAttributeOptions(npt, opts) {
  1484. var $npt = $(npt);
  1485. for (var option in opts) {
  1486. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  1487. if (optionData != undefined)
  1488. opts[option] = optionData;
  1489. }
  1490. return opts;
  1491. }
  1492. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1493. maskset;
  1494. if (typeof fn === "string") {
  1495. switch (fn) {
  1496. case "mask":
  1497. //resolve possible aliases given by options
  1498. resolveAlias(opts.alias, options, opts);
  1499. maskset = generateMaskSet(opts);
  1500. if (maskset.length == 0) { return this; }
  1501. return this.each(function () {
  1502. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, $.isArray(maskset) && targetScope === maskScope ? maskset[0] : maskset), importAttributeOptions(this, opts));
  1503. });
  1504. case "unmaskedvalue":
  1505. var $input = $(this);
  1506. if ($input.data(targetData)) {
  1507. return targetScope({ "action": "unmaskedvalue", "$input": $input });
  1508. } else return $input.val();
  1509. case "remove":
  1510. return this.each(function () {
  1511. var $input = $(this);
  1512. if ($input.data(targetData)) {
  1513. targetScope({ "action": "remove", "el": this });
  1514. }
  1515. });
  1516. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1517. if (this.data(targetData)) {
  1518. return targetScope({ "action": "getemptymask", "el": this });
  1519. }
  1520. else return "";
  1521. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1522. return this.data(targetData) ? !this.data(targetData)['opts'].autoUnmask : false;
  1523. case "isComplete":
  1524. if (this.data(targetData)) {
  1525. return targetScope({ "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
  1526. } else return true;
  1527. case "getmetadata": //return mask metadata if exists
  1528. if (this.data(targetData)) {
  1529. maskset = this.data(targetData)['maskset'];
  1530. return maskset['metadata'];
  1531. }
  1532. else return undefined;
  1533. case "_detectScope":
  1534. resolveAlias(opts.alias, options, opts);
  1535. if (msk != undefined && !resolveAlias(msk, options, opts) && $.inArray(msk, ["mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope"]) == -1) {
  1536. opts.mask = msk;
  1537. }
  1538. if ($.isFunction(opts.mask)) {
  1539. opts.mask = opts.mask.call(this, opts);
  1540. }
  1541. return $.isArray(opts.mask);
  1542. default:
  1543. resolveAlias(opts.alias, options, opts);
  1544. //check if the fn is an alias
  1545. if (!resolveAlias(fn, options, opts)) {
  1546. //maybe fn is a mask so we try
  1547. //set mask
  1548. opts.mask = fn;
  1549. }
  1550. maskset = generateMaskSet(opts);
  1551. if (maskset == undefined) { return this; }
  1552. return this.each(function () {
  1553. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, $.isArray(maskset) && targetScope === maskScope ? maskset[0] : maskset), importAttributeOptions(this, opts));
  1554. });
  1555. }
  1556. } else if (typeof fn == "object") {
  1557. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1558. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1559. maskset = generateMaskSet(opts);
  1560. if (maskset == undefined) { return this; }
  1561. return this.each(function () {
  1562. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, $.isArray(maskset) && targetScope === maskScope ? maskset[0] : maskset), importAttributeOptions(this, opts));
  1563. });
  1564. } else if (fn == undefined) {
  1565. //look for data-inputmask atribute - the attribute should only contain optipns
  1566. return this.each(function () {
  1567. var attrOptions = $(this).attr("data-inputmask");
  1568. if (attrOptions && attrOptions != "") {
  1569. try {
  1570. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1571. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1572. $.extend(true, dataoptions, options);
  1573. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1574. resolveAlias(opts.alias, dataoptions, opts);
  1575. opts.alias = undefined;
  1576. $(this).inputmask("mask", opts, targetScope);
  1577. } catch (ex) { } //need a more relax parseJSON
  1578. }
  1579. });
  1580. }
  1581. };
  1582. }
  1583. })(jQuery);