jquery.inputmask.js 103 KB

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