jquery.inputmask.js 104 KB

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