jquery.inputmask.js 120 KB

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