jquery.inputmask.js 111 KB

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