jquery.inputmask.js 120 KB

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