jquery.inputmask.js 103 KB

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