jquery.inputmask.js 126 KB

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