jquery.inputmask.js 121 KB

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