jquery.inputmask.js 109 KB

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