jquery.inputmask.js 119 KB

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