jquery.inputmask.js 111 KB

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