jquery.inputmask.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. /**
  2. * @license 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. eventName = 'on' + eventName,
  14. isSupported = (eventName in el);
  15. if (!isSupported) {
  16. el.setAttribute(eventName, 'return;');
  17. isSupported = typeof el[eventName] == 'function';
  18. }
  19. el = null;
  20. return isSupported;
  21. }
  22. function resolveAlias(aliasStr, options, opts) {
  23. var aliasDefinition = opts.aliases[aliasStr];
  24. if (aliasDefinition) {
  25. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  26. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  27. $.extend(true, opts, options); //reapply extra given options
  28. return true;
  29. }
  30. return false;
  31. }
  32. function generateMaskSet(opts) {
  33. var ms;
  34. function analyseMask(mask) {
  35. if (opts.numericInput) {
  36. mask = mask.split('').reverse().join('');
  37. }
  38. var tokenizer = /(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  39. escaped = false;
  40. function maskToken(isGroup, isOptional, isQuantifier) {
  41. this.matches = [];
  42. this.isGroup = isGroup || false;
  43. this.isOptional = isOptional || false;
  44. this.isQuantifier = isQuantifier || false;
  45. this.quantifier = { min: 1, max: 1 };
  46. };
  47. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
  48. function insertTestDefinition(mtoken, element, position) {
  49. var maskdef = opts.definitions[element];
  50. position = position != undefined ? position : mtoken.matches.length;
  51. if (maskdef && !escaped) {
  52. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  53. for (var i = 1; i < maskdef.cardinality; i++) {
  54. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  55. 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, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  56. }
  57. 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, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  58. } else {
  59. mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, casing: null, def: element });
  60. escaped = false;
  61. }
  62. }
  63. var currentToken = new maskToken(),
  64. match, m, openenings = [], maskTokens = [];
  65. while (match = tokenizer.exec(mask)) {
  66. m = match[0];
  67. switch (m.charAt(0)) {
  68. case opts.optionalmarker.end:
  69. // optional closing
  70. case opts.groupmarker.end:
  71. // Group closing
  72. var openingToken = openenings.pop();
  73. if (openenings.length > 0) {
  74. openenings[openenings.length - 1]["matches"].push(openingToken);
  75. } else {
  76. currentToken.matches.push(openingToken);
  77. }
  78. break;
  79. case opts.optionalmarker.start:
  80. // optional opening
  81. openenings.push(new maskToken(false, true));
  82. break;
  83. case opts.groupmarker.start:
  84. // Group opening
  85. openenings.push(new maskToken(true));
  86. break;
  87. case opts.quantifiermarker.start:
  88. //Quantifier
  89. var quantifier = new maskToken(false, false, true);
  90. m = m.replace(/[{}]/g, "");
  91. var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  92. quantifier.quantifier = { min: mq0, max: mq1 };
  93. if (openenings.length > 0) {
  94. var matches = openenings[openenings.length - 1]["matches"];
  95. var match = matches.pop();
  96. if (!match["isGroup"]) {
  97. var groupToken = new maskToken(true);
  98. groupToken.matches.push(match);
  99. match = groupToken;
  100. }
  101. matches.push(match);
  102. matches.push(quantifier);
  103. } else {
  104. var match = currentToken.matches.pop();
  105. if (!match["isGroup"]) {
  106. var groupToken = new maskToken(true);
  107. groupToken.matches.push(match);
  108. match = groupToken;
  109. }
  110. currentToken.matches.push(match);
  111. currentToken.matches.push(quantifier);
  112. }
  113. break;
  114. case opts.escapeChar:
  115. escaped = true;
  116. break;
  117. default:
  118. if (openenings.length > 0) {
  119. insertTestDefinition(openenings[openenings.length - 1], m);
  120. } else {
  121. if (currentToken.matches.length > 0) {
  122. var lastMatch = currentToken.matches[currentToken.matches.length - 1];
  123. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  124. lastMatch.isGroup = false;
  125. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  126. insertTestDefinition(lastMatch, opts.groupmarker.end);
  127. }
  128. }
  129. insertTestDefinition(currentToken, m);
  130. }
  131. }
  132. }
  133. if (currentToken.matches.length > 0)
  134. maskTokens.push(currentToken);
  135. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  136. var groupedMaskToken = new maskToken(false, false, false);
  137. var groupToken = new maskToken(true),
  138. quantifierToken = new maskToken(false, false, true);
  139. quantifierToken.quantifier = opts.repeat == "*" ? { min: 0, max: "*" } : (opts.repeat == "+" ? { min: 1, max: "*" } : { min: opts.greedy ? opts.repeat : 1, max: opts.repeat });
  140. if (maskTokens.length > 1) {
  141. groupToken.matches = maskTokens;
  142. groupedMaskToken.matches.push(groupToken);
  143. groupedMaskToken.matches.push(quantifierToken);
  144. } else {
  145. groupToken.matches = maskTokens[0].matches;
  146. groupedMaskToken.matches.push(groupToken);
  147. groupedMaskToken.matches.push(quantifierToken);
  148. }
  149. maskTokens = [groupedMaskToken];
  150. }
  151. console.log(JSON.stringify(maskTokens));
  152. return maskTokens;
  153. }
  154. function generateMask(mask, metadata) {
  155. return mask == undefined || mask == "" ? undefined : {
  156. "mask": mask,
  157. "maskToken": analyseMask(mask),
  158. "validPositions": {},
  159. "_buffer": undefined,
  160. "buffer": undefined,
  161. "tests": {},
  162. "metadata": metadata
  163. };
  164. }
  165. if (opts.repeat == "*" || opts.repeat == "+") opts.greedy = false;
  166. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  167. opts.mask = opts.mask.call(this, opts);
  168. }
  169. if ($.isArray(opts.mask)) {
  170. $.each(opts.mask, function (ndx, msk) {
  171. if (msk["mask"] != undefined) {
  172. ms = generateMask(msk["mask"].toString(), msk);
  173. } else {
  174. ms = generateMask(msk.toString());
  175. }
  176. return false; //break after first multiple not supported for now (again)
  177. });
  178. } else {
  179. if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  180. opts.placeholder = "";
  181. } //hide placeholder with single non-greedy mask
  182. if (opts.mask["mask"] != undefined) {
  183. ms = generateMask(opts.mask["mask"].toString(), opts.mask);
  184. } else {
  185. ms = generateMask(opts.mask.toString());
  186. }
  187. }
  188. return ms;
  189. }
  190. var msie1x = typeof ScriptEngineMajorVersion === "function"
  191. ? ScriptEngineMajorVersion() //IE11 detection
  192. : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
  193. ua = navigator.userAgent,
  194. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  195. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  196. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  197. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  198. 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),
  199. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  200. //if (androidchrome) {
  201. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  202. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  203. // androidchrome32 = (version == 32);
  204. //}
  205. //masking scope
  206. //actionObj definition see below
  207. function maskScope(maskset, opts, actionObj) {
  208. var isRTL = false,
  209. valueOnFocus = getBuffer().join(''),
  210. $el,
  211. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  212. skipInputEvent = false, //skip when triggered from within inputmask
  213. ignorable = false;
  214. //maskset helperfunctions
  215. function getMaskTemplate(baseOnInput, minimalPos) {
  216. minimalPos = minimalPos || 0;
  217. var maskTemplate = [], ndxIntlzr, pos = 0, test;
  218. do {
  219. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  220. var validPos = getMaskSet()['validPositions'][pos];
  221. test = validPos["match"];
  222. ndxIntlzr = validPos["locator"].slice();
  223. maskTemplate.push(test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  224. } else {
  225. var testPos = getTests(pos, false, ndxIntlzr, pos - 1);
  226. testPos = testPos[opts.greedy || minimalPos > pos ? 0 : (testPos.length - 1)];
  227. test = testPos["match"];
  228. ndxIntlzr = testPos["locator"].slice();
  229. maskTemplate.push(test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  230. }
  231. pos++;
  232. } while (test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  233. maskTemplate.pop(); //drop the last one which is empty
  234. return maskTemplate;
  235. }
  236. function getMaskSet() {
  237. return maskset;
  238. }
  239. function resetMaskSet() {
  240. var maskset = getMaskSet();
  241. maskset["buffer"] = undefined;
  242. maskset["_buffer"] = undefined;
  243. maskset["validPositions"] = {};
  244. maskset["p"] = -1;
  245. }
  246. function getLastValidPosition(maskset, closestTo) { //TODO implement closest to
  247. maskset = maskset || getMaskSet();
  248. var lastValidPosition = -1;
  249. for (var posNdx in maskset["validPositions"]) {
  250. var psNdx = parseInt(posNdx);
  251. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  252. }
  253. return lastValidPosition;
  254. }
  255. function setLastValidPosition(pos, maskset) {
  256. maskset = maskset || getMaskSet();
  257. for (var posNdx in maskset["validPositions"]) {
  258. if (posNdx > pos) maskset["validPositions"][posNdx] = undefined;
  259. }
  260. }
  261. function getTest(pos) {
  262. if (getMaskSet()['validPositions'][pos]) {
  263. return getMaskSet()['validPositions'][pos]["match"];
  264. }
  265. return getTests(pos)[0]["match"];
  266. }
  267. function getTests(pos, disableCache, ndxIntlzr, tstPs) {
  268. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  269. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  270. function handleMatch(match, loopNdx, quantifierRecurse) {
  271. var currentPos = testPos;
  272. if (testPos == pos && match.matches == undefined) {
  273. matches.push({ "match": match, "locator": loopNdx.reverse() });
  274. return true;
  275. } else if (match.matches != undefined) {
  276. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  277. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  278. if (match) return true;
  279. } else if (match.isOptional) {
  280. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  281. if (match) {
  282. //search for next possible match
  283. testPos = currentPos;
  284. }
  285. } else if (match.isQuantifier && quantifierRecurse !== true) {
  286. var qt = match;
  287. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  288. var tokenGroup = maskToken.matches[maskToken.matches.indexOf(qt) - 1];
  289. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  290. if (match) {
  291. //get latest match
  292. var latestMatch = matches[matches.length - 1]["match"];
  293. var isFirstMatch = (tokenGroup.matches.indexOf(latestMatch) == 0);
  294. if (isFirstMatch) { //search for next possible match
  295. if (qndx > qt.quantifier.min - 1) {
  296. insertStop = true;
  297. testPos = pos; //match the position after the group
  298. break; //stop quantifierloop
  299. } else return true;
  300. } else {
  301. return true;
  302. }
  303. }
  304. }
  305. } else {
  306. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  307. if (match)
  308. return true;
  309. }
  310. } else testPos++;
  311. }
  312. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  313. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  314. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  315. if (match && testPos == pos) {
  316. return match;
  317. } else if (testPos > pos) {
  318. break;
  319. }
  320. }
  321. }
  322. }
  323. if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  324. return getMaskSet()['tests'][pos];
  325. }
  326. if (ndxIntlzr == undefined) {
  327. var previousPos = pos - 1, test;
  328. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  329. previousPos--;
  330. }
  331. if (test != undefined && previousPos > -1) {
  332. testPos = previousPos;
  333. ndxInitializer = test["locator"].slice();
  334. } else {
  335. previousPos = pos - 1;
  336. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  337. previousPos--;
  338. }
  339. if (test != undefined && previousPos > -1) {
  340. testPos = previousPos;
  341. ndxInitializer = test[0]["locator"].slice();
  342. }
  343. }
  344. }
  345. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  346. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  347. if ((match && testPos == pos) || testPos > pos) {
  348. break;
  349. }
  350. }
  351. if (matches.length == 0 || insertStop)
  352. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  353. getMaskSet()['tests'][pos] = matches;
  354. console.log(pos + " - " + JSON.stringify(matches));
  355. return matches;
  356. }
  357. function getBufferTemplate() {
  358. if (getMaskSet()['_buffer'] == undefined) {
  359. //generate template
  360. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  361. }
  362. return getMaskSet()['_buffer'];
  363. }
  364. function getBuffer() {
  365. if (getMaskSet()['buffer'] == undefined) {
  366. getMaskSet()['buffer'] = getMaskTemplate(true);
  367. }
  368. return getMaskSet()['buffer'];
  369. }
  370. function isValid(pos, c, strict) { //strict true ~ no correction or autofill
  371. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  372. function _isValid(position, c, strict) {
  373. var rslt = false;
  374. $.each(getTests(position, !strict), function (ndx, tst) {
  375. var test = tst["match"];
  376. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  377. for (var i = test.cardinality; i > loopend; i--) {
  378. chrs += getBufferElement(buffer, position - (i - 1), true);
  379. }
  380. if (c) {
  381. chrs += c;
  382. }
  383. //return is false or a json object => { pos: ??, c: ??} or true
  384. rslt = test.fn != null ?
  385. test.fn.test(chrs, buffer, position, strict, opts)
  386. : (c == getPlaceholder(position) || c == opts.skipOptionalPartCharacter) ?
  387. { "refresh": true, c: getPlaceholder(position), pos: position }
  388. : false;
  389. if (rslt !== false) {
  390. var elem = c;
  391. switch (test.casing) {
  392. case "upper":
  393. elem = elem.toUpperCase();
  394. break;
  395. case "lower":
  396. elem = elem.toLowerCase();
  397. break;
  398. }
  399. var validatedPos = position;
  400. if (rslt !== true && rslt["pos"] != position) {
  401. validatedPos = rslt["pos"];
  402. tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO
  403. }
  404. getMaskSet()["validPositions"][validatedPos] = $.extend({}, tst, { "input": elem });
  405. return false; //break from $.each
  406. }
  407. });
  408. return rslt;
  409. }
  410. var maskPos = pos;
  411. var result = _isValid(maskPos, c, strict);
  412. if (!strict && result === false && !isMask(maskPos)) { //does the input match on a further position?
  413. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  414. result = _isValid(nPos, c, strict);
  415. if (result !== false) {
  416. maskPos = nPos;
  417. break;
  418. }
  419. }
  420. }
  421. if (result === true) result = { "pos": maskPos };
  422. return result;
  423. }
  424. function isMask(pos) {
  425. var test = getTest(pos);
  426. return test.fn != null ? test.fn : false;
  427. }
  428. function getMaskLength() {
  429. var maxLength = $el.prop('maxLength'), maskLength;
  430. if (opts.greedy == false) {
  431. var lvp = getLastValidPosition() + 1,
  432. test = getTest(lvp);
  433. while (test.fn != null && test.def != "") {
  434. var tests = getTests(++lvp);
  435. test = tests[tests.length - 1];
  436. }
  437. maskLength = getMaskTemplate(false, lvp).length;
  438. } else
  439. maskLength = getBuffer().length;
  440. return maxLength == undefined || (maskLength < maxLength && maxLength > -1) /* FF sets no defined max length to -1 */ ? maskLength : maxLength;
  441. }
  442. function seekNext(pos) {
  443. var maskL = getMaskLength();
  444. if (pos >= maskL) return maskL;
  445. var position = pos;
  446. while (++position < maskL && !isMask(position)) {
  447. }
  448. return position;
  449. }
  450. function seekPrevious(pos) {
  451. var position = pos;
  452. if (position <= 0) return 0;
  453. while (--position > 0 && !isMask(position)) {
  454. }
  455. ;
  456. return position;
  457. }
  458. function setBufferElement(buffer, position, element) {
  459. position = prepareBuffer(buffer, position);
  460. var test = getTest(position);
  461. var elem = element;
  462. if (elem != undefined && test != undefined) {
  463. switch (test.casing) {
  464. case "upper":
  465. elem = element.toUpperCase();
  466. break;
  467. case "lower":
  468. elem = element.toLowerCase();
  469. break;
  470. }
  471. }
  472. buffer[position] = elem;
  473. }
  474. function getBufferElement(buffer, position) {
  475. position = prepareBuffer(buffer, position);
  476. return buffer[position];
  477. }
  478. //needed to handle the non-greedy mask repetitions
  479. function prepareBuffer(buffer, position) { //TODO DROP BUFFER PASSING + optimize me
  480. if (buffer.length <= position) {
  481. var trbuffer = getMaskTemplate(true, position);
  482. buffer.length = trbuffer.length;
  483. for (var i = 0, bl = buffer.length; i < bl; i++) {
  484. if (buffer[i] == undefined)
  485. buffer[i] = trbuffer[i];
  486. }
  487. buffer[position] = getPlaceholder(position);
  488. }
  489. return position;
  490. }
  491. function writeBuffer(input, buffer, caretPos) {
  492. input._valueSet(buffer.join(''));
  493. if (caretPos != undefined) {
  494. caret(input, caretPos);
  495. }
  496. }
  497. function clearBuffer(buffer, start, end, stripNomasks) {
  498. for (var i = start, maskL = getMaskLength() ; i < end && i < maskL; i++) {
  499. if (stripNomasks === true) {
  500. if (!isMask(i))
  501. setBufferElement(buffer, i, "");
  502. } else
  503. setBufferElement(buffer, i, getPlaceholder(i));
  504. }
  505. }
  506. function setPlaceholder(pos) {
  507. setBufferElement(getBuffer(), pos, getPlaceholder(pos));
  508. }
  509. function getPlaceholder(pos) {
  510. var test = getTest(pos);
  511. return test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length);
  512. }
  513. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  514. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  515. resetMaskSet();
  516. if (writeOut) input._valueSet(""); //initial clear
  517. $.each(inputValue, function (ndx, charCode) {
  518. if (intelliCheck === true) {
  519. var p = getMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p),
  520. pos = lvp == -1 ? ndx : seekNext(lvp);
  521. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
  522. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  523. }
  524. } else {
  525. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  526. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  527. }
  528. });
  529. }
  530. function escapeRegex(str) {
  531. return $.inputmask.escapeRegex.call(this, str);
  532. }
  533. function truncateInput(inputValue) {
  534. return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
  535. }
  536. function clearOptionalTail(input) {
  537. var buffer = getBuffer(), tmpBuffer = buffer.slice(), testPos, pos;
  538. for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  539. if (getTest(pos).optionality) {
  540. if (!isMask(pos) || !isValid(pos, buffer[pos], true))
  541. tmpBuffer.pop();
  542. else break;
  543. } else break;
  544. }
  545. writeBuffer(input, tmpBuffer);
  546. }
  547. function unmaskedvalue($input, skipDatepickerCheck) {
  548. if ($input.data('_inputmask') && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  549. var umValue = $.map(getBuffer(), function (element, index) {
  550. return isMask(index) && isValid(index, element, true) ? element : null;
  551. });
  552. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  553. return $.isFunction(opts.onUnMask) ? opts.onUnMask.call($input, getBuffer().join(''), unmaskedValue, opts) : unmaskedValue;
  554. } else {
  555. return $input[0]._valueGet();
  556. }
  557. }
  558. function TranslatePosition(pos) {
  559. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  560. var bffrLght = getBuffer().length;
  561. pos = bffrLght - pos;
  562. }
  563. return pos;
  564. }
  565. function caret(input, begin, end) {
  566. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  567. if (typeof begin == 'number') {
  568. begin = TranslatePosition(begin);
  569. end = TranslatePosition(end);
  570. if (!$(npt).is(':visible')) {
  571. return;
  572. }
  573. end = (typeof end == 'number') ? end : begin;
  574. npt.scrollLeft = npt.scrollWidth;
  575. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  576. if (npt.setSelectionRange) {
  577. npt.selectionStart = begin;
  578. npt.selectionEnd = end;
  579. } else if (npt.createTextRange) {
  580. range = npt.createTextRange();
  581. range.collapse(true);
  582. range.moveEnd('character', end);
  583. range.moveStart('character', begin);
  584. range.select();
  585. }
  586. } else {
  587. if (!$(input).is(':visible')) {
  588. return { "begin": 0, "end": 0 };
  589. }
  590. if (npt.setSelectionRange) {
  591. begin = npt.selectionStart;
  592. end = npt.selectionEnd;
  593. } else if (document.selection && document.selection.createRange) {
  594. range = document.selection.createRange();
  595. begin = 0 - range.duplicate().moveStart('character', -100000);
  596. end = begin + range.text.length;
  597. }
  598. begin = TranslatePosition(begin);
  599. end = TranslatePosition(end);
  600. return { "begin": begin, "end": end };
  601. }
  602. }
  603. function isComplete(buffer) { //return true / false / undefined (repeat *)
  604. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  605. if (opts.repeat == "*") return undefined;
  606. var complete = false,
  607. aml = seekPrevious(getMaskLength());
  608. if (getLastValidPosition() == aml) {
  609. complete = true;
  610. for (var i = 0; i <= aml; i++) {
  611. var mask = isMask(i);
  612. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  613. complete = false;
  614. break;
  615. }
  616. }
  617. }
  618. return complete;
  619. }
  620. function isSelection(begin, end) {
  621. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  622. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  623. }
  624. function installEventRuler(npt) {
  625. var events = $._data(npt).events;
  626. $.each(events, function (eventType, eventHandlers) {
  627. $.each(eventHandlers, function (ndx, eventHandler) {
  628. if (eventHandler.namespace == "inputmask") {
  629. if (eventHandler.type != "setvalue") {
  630. var handler = eventHandler.handler;
  631. eventHandler.handler = function (e) {
  632. if (this.readOnly || this.disabled)
  633. e.preventDefault;
  634. else
  635. return handler.apply(this, arguments);
  636. };
  637. }
  638. }
  639. });
  640. });
  641. }
  642. function patchValueProperty(npt) {
  643. function PatchValhook(type) {
  644. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  645. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  646. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  647. elem.value = value;
  648. return elem;
  649. };
  650. $.valHooks[type] = {
  651. get: function (elem) {
  652. var $elem = $(elem);
  653. if ($elem.data('_inputmask')) {
  654. if ($elem.data('_inputmask')['opts'].autoUnmask)
  655. return $elem.inputmask('unmaskedvalue');
  656. else {
  657. var result = valueGet(elem),
  658. inputData = $elem.data('_inputmask'), maskset = inputData['maskset'],
  659. bufferTemplate = maskset['_buffer'];
  660. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  661. return result != bufferTemplate ? result : '';
  662. }
  663. } else return valueGet(elem);
  664. },
  665. set: function (elem, value) {
  666. var $elem = $(elem);
  667. var result = valueSet(elem, value);
  668. if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
  669. return result;
  670. },
  671. inputmaskpatch: true
  672. };
  673. }
  674. }
  675. var valueProperty;
  676. if (Object.getOwnPropertyDescriptor)
  677. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  678. if (valueProperty && valueProperty.get) {
  679. if (!npt._valueGet) {
  680. var valueGet = valueProperty.get;
  681. var valueSet = valueProperty.set;
  682. npt._valueGet = function () {
  683. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  684. };
  685. npt._valueSet = function (value) {
  686. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  687. };
  688. Object.defineProperty(npt, "value", {
  689. get: function () {
  690. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  691. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  692. },
  693. set: function (value) {
  694. valueSet.call(this, value);
  695. $(this).triggerHandler('setvalue.inputmask');
  696. }
  697. });
  698. }
  699. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  700. if (!npt._valueGet) {
  701. var valueGet = npt.__lookupGetter__("value");
  702. var valueSet = npt.__lookupSetter__("value");
  703. npt._valueGet = function () {
  704. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  705. };
  706. npt._valueSet = function (value) {
  707. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  708. };
  709. npt.__defineGetter__("value", function () {
  710. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  711. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  712. });
  713. npt.__defineSetter__("value", function (value) {
  714. valueSet.call(this, value);
  715. $(this).triggerHandler('setvalue.inputmask');
  716. });
  717. }
  718. } else {
  719. if (!npt._valueGet) {
  720. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  721. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  722. }
  723. PatchValhook(npt.type);
  724. }
  725. }
  726. //shift chars to left from start to end and put c at end position if defined
  727. function shiftL(start, end, c, maskJumps) {
  728. var buffer = getBuffer();
  729. if (maskJumps !== false) //jumping over nonmask position
  730. while (!isMask(start) && start - 1 >= 0) start--;
  731. for (var i = start; i < end && i < getMaskLength() ; i++) {
  732. if (isMask(i)) {
  733. setPlaceholder(i);
  734. var j = seekNext(i);
  735. var p = getBufferElement(buffer, j);
  736. if (p != getPlaceholder(j)) {
  737. if (j < getMaskLength() && isValid(i, p, true) !== false && getTest(i).def == getTest(j).def) {
  738. setBufferElement(buffer, i, p);
  739. if (j < end) {
  740. setPlaceholder(j); //cleanup next position
  741. }
  742. } else {
  743. if (isMask(i))
  744. break;
  745. }
  746. }
  747. } else {
  748. setPlaceholder(i);
  749. }
  750. }
  751. if (c != undefined)
  752. setBufferElement(buffer, seekPrevious(end), c);
  753. if (opts.greedy == false) {
  754. var trbuffer = truncateInput(buffer.join('')).split('');
  755. buffer.length = trbuffer.length;
  756. for (var i = 0, bl = buffer.length; i < bl; i++) {
  757. buffer[i] = trbuffer[i];
  758. }
  759. if (buffer.length == 0) getMaskSet()["buffer"] = getBufferTemplate().slice();
  760. }
  761. return start; //return the used start position
  762. }
  763. function shiftR(start, end, c) {
  764. var buffer = getBuffer();
  765. if (getBufferElement(buffer, start) != getPlaceholder(start)) {
  766. for (var i = seekPrevious(end) ; i > start && i >= 0; i--) {
  767. if (isMask(i)) {
  768. var j = seekPrevious(i);
  769. var t = getBufferElement(buffer, j);
  770. if (t != getPlaceholder(j)) {
  771. if (isValid(i, t, true) !== false && getTest(i).def == getTest(j).def) {
  772. setBufferElement(buffer, i, t);
  773. setPlaceholder(j);
  774. } //else break;
  775. }
  776. } else
  777. setPlaceholder(i);
  778. }
  779. }
  780. if (c != undefined && getBufferElement(buffer, start) == getPlaceholder(start))
  781. setBufferElement(buffer, start, c);
  782. var lengthBefore = buffer.length;
  783. if (opts.greedy == false) {
  784. var trbuffer = truncateInput(buffer.join('')).split('');
  785. buffer.length = trbuffer.length;
  786. for (var i = 0, bl = buffer.length; i < bl; i++) {
  787. buffer[i] = trbuffer[i];
  788. }
  789. if (buffer.length == 0) getMaskSet()["buffer"] = getBufferTemplate().slice();
  790. }
  791. return end - (lengthBefore - buffer.length); //return new start position
  792. }
  793. function HandleRemove(input, k, pos) {
  794. if (opts.numericInput || isRTL) {
  795. switch (k) {
  796. case opts.keyCode.BACKSPACE:
  797. k = opts.keyCode.DELETE;
  798. break;
  799. case opts.keyCode.DELETE:
  800. k = opts.keyCode.BACKSPACE;
  801. break;
  802. }
  803. if (isRTL) {
  804. var pend = pos.end;
  805. pos.end = pos.begin;
  806. pos.begin = pend;
  807. }
  808. }
  809. var isSelection = true;
  810. if (pos.begin == pos.end) {
  811. var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
  812. if (opts.isNumeric && opts.radixPoint != "" && getBuffer()[posBegin] == opts.radixPoint) {
  813. pos.begin = (getBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
  814. pos.end = pos.begin;
  815. }
  816. isSelection = false;
  817. if (k == opts.keyCode.BACKSPACE)
  818. pos.begin--;
  819. else if (k == opts.keyCode.DELETE)
  820. pos.end++;
  821. } else if (pos.end - pos.begin == 1 && !opts.insertMode) {
  822. isSelection = false;
  823. if (k == opts.keyCode.BACKSPACE)
  824. pos.begin--;
  825. }
  826. clearBuffer(getBuffer(), pos.begin, pos.end);
  827. var ml = getMaskLength();
  828. if (opts.greedy == false && (isNaN(opts.repeat) || opts.repeat > 0)) {
  829. shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
  830. } else {
  831. var newpos = pos.begin;
  832. for (var i = pos.begin; i < pos.end; i++) { //seeknext to skip placeholders at start in selection
  833. if (isMask(i) || !isSelection)
  834. newpos = shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
  835. }
  836. if (!isSelection) pos.begin = newpos;
  837. }
  838. var firstMaskPos = seekNext(-1);
  839. clearBuffer(getBuffer(), pos.begin, pos.end, true);
  840. checkVal(input, false, false, getBuffer());
  841. if (getLastValidPosition() < firstMaskPos) {
  842. getMaskSet()["p"] = firstMaskPos;
  843. } else {
  844. getMaskSet()["p"] = pos.begin;
  845. }
  846. }
  847. function keydownEvent(e) {
  848. //Safari 5.1.x - modal dialog fires keypress twice workaround
  849. skipKeyPressEvent = false;
  850. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  851. //backspace, delete, and escape get special treatment
  852. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  853. e.preventDefault(); //stop default action but allow propagation
  854. if (k == 88) valueOnFocus = getBuffer().join('');
  855. HandleRemove(input, k, pos);
  856. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  857. if (input._valueGet() == getBufferTemplate().join(''))
  858. $input.trigger('cleared');
  859. if (opts.showTooltip) { //update tooltip
  860. $input.prop("title", getMaskSet()["mask"]);
  861. }
  862. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  863. setTimeout(function () {
  864. var caretPos = seekNext(getLastValidPosition());
  865. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  866. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  867. }, 0);
  868. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  869. caret(input, 0, e.shiftKey ? pos.begin : 0);
  870. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  871. checkVal(input, true, false, valueOnFocus.split(''));
  872. $input.click();
  873. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  874. opts.insertMode = !opts.insertMode;
  875. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  876. } else if (opts.insertMode == false && !e.shiftKey) {
  877. if (k == opts.keyCode.RIGHT) {
  878. setTimeout(function () {
  879. var caretPos = caret(input);
  880. caret(input, caretPos.begin);
  881. }, 0);
  882. } else if (k == opts.keyCode.LEFT) {
  883. setTimeout(function () {
  884. var caretPos = caret(input);
  885. caret(input, caretPos.begin - 1);
  886. }, 0);
  887. }
  888. }
  889. var currentCaretPos = caret(input);
  890. if (opts.onKeyDown.call(this, e, getBuffer(), opts) === true) //extra stuff to execute on keydown
  891. caret(input, currentCaretPos.begin, currentCaretPos.end);
  892. ignorable = $.inArray(k, opts.ignorables) != -1;
  893. }
  894. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  895. //Safari 5.1.x - modal dialog fires keypress twice workaround
  896. if (k == undefined && skipKeyPressEvent) return false;
  897. skipKeyPressEvent = true;
  898. var input = this, $input = $(input);
  899. e = e || window.event;
  900. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  901. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  902. return true;
  903. } else {
  904. if (k) {
  905. //special treat the decimal separator
  906. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  907. var pos, forwardPosition, c = String.fromCharCode(k);
  908. if (checkval) {
  909. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  910. pos = { begin: pcaret, end: pcaret };
  911. } else {
  912. pos = caret(input);
  913. }
  914. //should we clear a possible selection??
  915. var isSlctn = isSelection(pos.begin, pos.end);
  916. if (isSlctn) {
  917. getMaskSet()["undoBuffer"] = getBuffer().join(''); //init undobuffer for recovery when not valid
  918. HandleRemove(input, opts.keyCode.DELETE, pos);
  919. if (!opts.insertMode) { //preserve some space
  920. shiftR(pos.begin, getMaskLength());
  921. }
  922. }
  923. var radixPosition = getBuffer().join('').indexOf(opts.radixPoint);
  924. if (opts.isNumeric && checkval !== true && radixPosition != -1) {
  925. if (opts.greedy && pos.begin <= radixPosition) {
  926. pos.begin = seekPrevious(pos.begin);
  927. pos.end = pos.begin;
  928. } else if (c == opts.radixPoint) {
  929. pos.begin = radixPosition;
  930. pos.end = pos.begin;
  931. }
  932. }
  933. getMaskSet()["writeOutBuffer"] = true;
  934. var p = pos.begin;
  935. var valResult = isValid(p, c, strict);
  936. if (valResult !== false) {
  937. var refresh = false, buffer = getBuffer();
  938. if (valResult !== true) {
  939. refresh = valResult["refresh"]; //only rewrite buffer from isValid
  940. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  941. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  942. }
  943. if (refresh !== true) {
  944. if (opts.insertMode == true) {
  945. var freePos = p;
  946. if (getBufferElement(buffer, p) != getPlaceholder(p)) {
  947. while (getMaskSet()["validPositions"][freePos]) {
  948. freePos = seekNext(freePos);
  949. }
  950. }
  951. if (freePos < getMaskLength()) {
  952. shiftR(p, getMaskLength(), c);
  953. } else getMaskSet()["writeOutBuffer"] = false;
  954. } else setBufferElement(buffer, p, c);
  955. }
  956. forwardPosition = seekNext(p);
  957. getMaskSet()["p"] = forwardPosition; //needed for checkval
  958. }
  959. if (writeOut !== false) {
  960. var self = this;
  961. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  962. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  963. var buffer = getBuffer();
  964. var newCaretPosition;
  965. if (checkval) {
  966. newCaretPosition = undefined;
  967. } else if (opts.numericInput) {
  968. if (p > radixPosition) {
  969. newCaretPosition = seekPrevious(forwardPosition);
  970. } else if (c == opts.radixPoint) {
  971. newCaretPosition = forwardPosition - 1;
  972. } else newCaretPosition = seekPrevious(forwardPosition - 1);
  973. } else {
  974. newCaretPosition = forwardPosition;
  975. }
  976. writeBuffer(input, buffer, newCaretPosition);
  977. if (checkval !== true) {
  978. setTimeout(function () { //timeout needed for IE
  979. if (isComplete(buffer) === true)
  980. $input.trigger("complete");
  981. skipInputEvent = true;
  982. $input.trigger("input");
  983. }, 0);
  984. }
  985. } else if (isSlctn) { //TODO FIXME
  986. getMaskSet()["buffer"] = getMaskSet()["undoBuffer"].split('');
  987. }
  988. } else if (isSlctn) { //TODO FIXME
  989. getMaskSet()["buffer"] = getMaskSet()["undoBuffer"].split('');
  990. }
  991. if (opts.showTooltip) { //update tooltip
  992. $input.prop("title", getMaskSet()["mask"]);
  993. }
  994. //needed for IE8 and below
  995. if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false;
  996. }
  997. }
  998. }
  999. function keyupEvent(e) {
  1000. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  1001. opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup
  1002. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  1003. if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  1004. buffer = getBufferTemplate().slice();
  1005. writeBuffer(input, buffer);
  1006. caret(input, 0);
  1007. valueOnFocus = getBuffer().join('');
  1008. } else {
  1009. writeBuffer(input, buffer);
  1010. if (buffer.join('') == getBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) {
  1011. caret(input, TranslatePosition(0));
  1012. $input.click();
  1013. } else
  1014. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  1015. }
  1016. }
  1017. }
  1018. function pasteEvent(e) {
  1019. if (skipInputEvent === true && e.type == "input") {
  1020. skipInputEvent = false;
  1021. return true;
  1022. }
  1023. var input = this, $input = $(input);
  1024. //paste event for IE8 and lower I guess ;-)
  1025. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1026. return true;
  1027. }
  1028. setTimeout(function () {
  1029. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, input._valueGet(), opts) : input._valueGet();
  1030. checkVal(input, false, false, pasteValue.split(''), true);
  1031. writeBuffer(input, getBuffer());
  1032. if (isComplete(getBuffer()) === true)
  1033. $input.trigger("complete");
  1034. $input.click();
  1035. }, 0);
  1036. }
  1037. //not used - attempt to support android
  1038. function mobileInputEvent(e) {
  1039. var input = this, $input = $(input);
  1040. //backspace in chrome32 only fires input event - detect & treat
  1041. var caretPos = caret(input),
  1042. currentValue = input._valueGet();
  1043. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1044. //correct caretposition for chrome
  1045. if (caretPos.begin > currentValue.length) {
  1046. caret(input, currentValue.length);
  1047. caretPos = caret(input);
  1048. }
  1049. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1050. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1051. && !isMask(caretPos.begin)) {
  1052. e.keyCode = opts.keyCode.BACKSPACE;
  1053. keydownEvent.call(input, e);
  1054. } else { //nonnumerics don't fire keypress
  1055. checkVal(input, false, false, currentValue.split(''));
  1056. writeBuffer(input, getBuffer());
  1057. if (isComplete(getBuffer()) === true)
  1058. $input.trigger("complete");
  1059. $input.click();
  1060. }
  1061. e.preventDefault();
  1062. }
  1063. function mask(el) {
  1064. $el = $(el);
  1065. if ($el.is(":input")) {
  1066. //store tests & original buffer in the input element - used to get the unmasked value
  1067. $el.data('_inputmask', {
  1068. 'maskset': maskset,
  1069. 'opts': opts,
  1070. 'isRTL': false
  1071. });
  1072. //show tooltip
  1073. if (opts.showTooltip) {
  1074. $el.prop("title", getMaskSet()["mask"]);
  1075. }
  1076. //correct greedy setting if needed
  1077. opts.greedy = opts.greedy ? opts.greedy : opts.repeat == 0;
  1078. patchValueProperty(el);
  1079. if (opts.numericInput) opts.isNumeric = opts.numericInput;
  1080. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1081. $el.css("text-align", "right");
  1082. if (el.dir == "rtl" || opts.numericInput) {
  1083. el.dir = "ltr";
  1084. $el.removeAttr("dir");
  1085. var inputData = $el.data('_inputmask');
  1086. inputData['isRTL'] = true;
  1087. $el.data('_inputmask', inputData);
  1088. isRTL = true;
  1089. }
  1090. //unbind all events - to make sure that no other mask will interfere when re-masking
  1091. $el.unbind(".inputmask");
  1092. $el.removeClass('focus.inputmask');
  1093. //bind events
  1094. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1095. if (valueOnFocus != getBuffer().join('')) {
  1096. $el.change();
  1097. }
  1098. }).bind('reset', function () {
  1099. setTimeout(function () {
  1100. $el.trigger("setvalue");
  1101. }, 0);
  1102. });
  1103. $el.bind("mouseenter.inputmask", function () {
  1104. var $input = $(this), input = this;
  1105. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  1106. if (input._valueGet() != getBuffer().join('')) {
  1107. writeBuffer(input, getBuffer());
  1108. }
  1109. }
  1110. }).bind("blur.inputmask", function () {
  1111. var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getBuffer();
  1112. $input.removeClass('focus.inputmask');
  1113. if (valueOnFocus != getBuffer().join('')) {
  1114. $input.change();
  1115. }
  1116. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1117. if (nptValue == getBufferTemplate().join(''))
  1118. input._valueSet('');
  1119. else { //clearout optional tail of the mask
  1120. clearOptionalTail(input);
  1121. }
  1122. }
  1123. if (isComplete(buffer) === false) {
  1124. $input.trigger("incomplete");
  1125. if (opts.clearIncomplete) {
  1126. resetMaskSet();
  1127. if (opts.clearMaskOnLostFocus)
  1128. input._valueSet('');
  1129. else {
  1130. buffer = getBufferTemplate().slice();
  1131. writeBuffer(input, buffer);
  1132. }
  1133. }
  1134. }
  1135. }).bind("focus.inputmask", function () {
  1136. var $input = $(this), input = this, nptValue = input._valueGet();
  1137. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1138. if (input._valueGet() != getBuffer().join('')) {
  1139. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1140. }
  1141. }
  1142. $input.addClass('focus.inputmask');
  1143. valueOnFocus = getBuffer().join('');
  1144. }).bind("mouseleave.inputmask", function () {
  1145. var $input = $(this), input = this;
  1146. if (opts.clearMaskOnLostFocus) {
  1147. if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1148. if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
  1149. input._valueSet('');
  1150. else { //clearout optional tail of the mask
  1151. clearOptionalTail(input);
  1152. }
  1153. }
  1154. }
  1155. }).bind("click.inputmask", function () {
  1156. var input = this;
  1157. setTimeout(function () {
  1158. var selectedCaret = caret(input), buffer = getBuffer();
  1159. if (selectedCaret.begin == selectedCaret.end) {
  1160. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1161. lvp = getLastValidPosition(undefined, clickPosition),
  1162. lastPosition;
  1163. if (opts.isNumeric) {
  1164. lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
  1165. (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
  1166. seekNext(lvp);
  1167. } else {
  1168. lastPosition = seekNext(lvp);
  1169. }
  1170. if (clickPosition < lastPosition) {
  1171. if (isMask(clickPosition))
  1172. caret(input, clickPosition);
  1173. else caret(input, seekNext(clickPosition));
  1174. } else
  1175. caret(input, lastPosition);
  1176. }
  1177. }, 0);
  1178. }).bind('dblclick.inputmask', function () {
  1179. var input = this;
  1180. setTimeout(function () {
  1181. caret(input, 0, seekNext(getLastValidPosition()));
  1182. }, 0);
  1183. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1184. ).bind('setvalue.inputmask', function () {
  1185. var input = this;
  1186. checkVal(input, true);
  1187. valueOnFocus = getBuffer().join('');
  1188. if (input._valueGet() == getBufferTemplate().join(''))
  1189. input._valueSet('');
  1190. }).bind('complete.inputmask', opts.oncomplete
  1191. ).bind('incomplete.inputmask', opts.onincomplete
  1192. ).bind('cleared.inputmask', opts.oncleared);
  1193. $el.bind("keydown.inputmask", keydownEvent
  1194. ).bind("keypress.inputmask", keypressEvent
  1195. ).bind("keyup.inputmask", keyupEvent);
  1196. // as the other inputevents aren't reliable for the moment we only base on the input event
  1197. // needs follow-up
  1198. if (android || androidfirefox || androidchrome || kindle) {
  1199. $el.attr("autocomplete", "off")
  1200. .attr("autocorrect", "off")
  1201. .attr("autocapitalize", "off")
  1202. .attr("spellcheck", false);
  1203. if (androidfirefox || kindle) {
  1204. $el.unbind("keydown.inputmask", keydownEvent
  1205. ).unbind("keypress.inputmask", keypressEvent
  1206. ).unbind("keyup.inputmask", keyupEvent);
  1207. if (PasteEventType == "input") {
  1208. $el.unbind(PasteEventType + ".inputmask");
  1209. }
  1210. $el.bind("input.inputmask", mobileInputEvent);
  1211. }
  1212. }
  1213. if (msie1x)
  1214. $el.bind("input.inputmask", pasteEvent);
  1215. //apply mask
  1216. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1217. checkVal(el, true, false, initialValue.split(''), true);
  1218. valueOnFocus = getBuffer().join('');
  1219. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1220. var activeElement;
  1221. try {
  1222. activeElement = document.activeElement;
  1223. } catch (e) {
  1224. }
  1225. if (activeElement === el) { //position the caret when in focus
  1226. $el.addClass('focus.inputmask');
  1227. caret(el, seekNext(getLastValidPosition()));
  1228. } else if (opts.clearMaskOnLostFocus) {
  1229. if (getBuffer().join('') == getBufferTemplate().join('')) {
  1230. el._valueSet('');
  1231. } else {
  1232. clearOptionalTail(el);
  1233. }
  1234. } else {
  1235. writeBuffer(el, getBuffer());
  1236. }
  1237. installEventRuler(el);
  1238. }
  1239. }
  1240. //action object
  1241. if (actionObj != undefined) {
  1242. switch (actionObj["action"]) {
  1243. case "isComplete":
  1244. return isComplete(actionObj["buffer"]);
  1245. case "unmaskedvalue":
  1246. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1247. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1248. case "mask":
  1249. mask(actionObj["el"]);
  1250. break;
  1251. case "format":
  1252. $el = $({});
  1253. $el.data('_inputmask', {
  1254. 'maskset': maskset,
  1255. 'opts': opts,
  1256. 'isRTL': opts.numericInput
  1257. });
  1258. if (opts.numericInput) {
  1259. opts.isNumeric = opts.numericInput;
  1260. isRTL = true;
  1261. }
  1262. checkVal($el, false, false, actionObj["value"].split(''), true);
  1263. return getBuffer().join('');
  1264. case "isValid":
  1265. $el = $({});
  1266. $el.data('_inputmask', {
  1267. 'maskset': maskset,
  1268. 'opts': opts,
  1269. 'isRTL': opts.numericInput
  1270. });
  1271. if (opts.numericInput) {
  1272. opts.isNumeric = opts.numericInput;
  1273. isRTL = true;
  1274. }
  1275. checkVal($el, false, true, actionObj["value"].split(''));
  1276. return isComplete(getBuffer());
  1277. }
  1278. }
  1279. };
  1280. $.inputmask = {
  1281. //options default
  1282. defaults: {
  1283. placeholder: "_",
  1284. optionalmarker: { start: "[", end: "]" },
  1285. quantifiermarker: { start: "{", end: "}" },
  1286. groupmarker: { start: "(", end: ")" },
  1287. escapeChar: "\\",
  1288. mask: null,
  1289. oncomplete: $.noop, //executes when the mask is complete
  1290. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1291. oncleared: $.noop, //executes when the mask is cleared
  1292. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1293. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1294. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1295. clearMaskOnLostFocus: true,
  1296. insertMode: true, //insert the input or overwrite the input
  1297. clearIncomplete: false, //clear the incomplete input on blur
  1298. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1299. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  1300. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  1301. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1302. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1303. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1304. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1305. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1306. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1307. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1308. showTooltip: false, //show the activemask as tooltip
  1309. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1310. //numeric basic properties
  1311. isNumeric: false, //enable numeric features
  1312. radixPoint: "", //".", // | ","
  1313. skipRadixDance: false, //disable radixpoint caret positioning
  1314. rightAlignNumerics: true, //align numerics to the right
  1315. //numeric basic properties
  1316. definitions: {
  1317. '9': {
  1318. validator: "[0-9]",
  1319. cardinality: 1,
  1320. definitionSymbol: "*"
  1321. },
  1322. 'a': {
  1323. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1324. cardinality: 1,
  1325. definitionSymbol: "*"
  1326. },
  1327. '*': {
  1328. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1329. cardinality: 1
  1330. }
  1331. },
  1332. keyCode: {
  1333. 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,
  1334. 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
  1335. },
  1336. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1337. 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],
  1338. isComplete: undefined //override for isComplete - args => buffer, opts - return true || false
  1339. },
  1340. escapeRegex: function (str) {
  1341. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1342. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1343. },
  1344. format: function (value, options) {
  1345. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1346. resolveAlias(opts.alias, options, opts);
  1347. return maskScope(generateMaskSet(opts), opts, { "action": "format", "value": value });
  1348. },
  1349. isValid: function (value, options) {
  1350. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1351. resolveAlias(opts.alias, options, opts);
  1352. return maskScope(generateMaskSet(opts), opts, { "action": "isValid", "value": value });
  1353. }
  1354. };
  1355. $.fn.inputmask = function (fn, options) {
  1356. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1357. maskset;
  1358. if (typeof fn === "string") {
  1359. switch (fn) {
  1360. case "mask":
  1361. //resolve possible aliases given by options
  1362. resolveAlias(opts.alias, options, opts);
  1363. maskset = generateMaskSet(opts);
  1364. if (maskset.length == 0) { return this; }
  1365. return this.each(function () {
  1366. maskScope($.extend(true, {}, maskset), 0, opts, { "action": "mask", "el": this });
  1367. });
  1368. case "unmaskedvalue":
  1369. var $input = $(this), input = this;
  1370. if ($input.data('_inputmask')) {
  1371. maskset = $input.data('_inputmask')['maskset'];
  1372. opts = $input.data('_inputmask')['opts'];
  1373. return maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input });
  1374. } else return $input.val();
  1375. case "remove":
  1376. return this.each(function () {
  1377. var $input = $(this), input = this;
  1378. if ($input.data('_inputmask')) {
  1379. maskset = $input.data('_inputmask')['maskset'];
  1380. opts = $input.data('_inputmask')['opts'];
  1381. //writeout the unmaskedvalue
  1382. input._valueSet(maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true }));
  1383. //clear data
  1384. $input.removeData('_inputmask');
  1385. //unbind all events
  1386. $input.unbind(".inputmask");
  1387. $input.removeClass('focus.inputmask');
  1388. //restore the value property
  1389. var valueProperty;
  1390. if (Object.getOwnPropertyDescriptor)
  1391. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  1392. if (valueProperty && valueProperty.get) {
  1393. if (input._valueGet) {
  1394. Object.defineProperty(input, "value", {
  1395. get: input._valueGet,
  1396. set: input._valueSet
  1397. });
  1398. }
  1399. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  1400. if (input._valueGet) {
  1401. input.__defineGetter__("value", input._valueGet);
  1402. input.__defineSetter__("value", input._valueSet);
  1403. }
  1404. }
  1405. try { //try catch needed for IE7 as it does not supports deleting fns
  1406. delete input._valueGet;
  1407. delete input._valueSet;
  1408. } catch (e) {
  1409. input._valueGet = undefined;
  1410. input._valueSet = undefined;
  1411. }
  1412. }
  1413. });
  1414. break;
  1415. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1416. if (this.data('_inputmask')) {
  1417. maskset = this.data('_inputmask')['maskset'];
  1418. return maskset['_buffer'].join('');
  1419. }
  1420. else return "";
  1421. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1422. return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
  1423. case "isComplete":
  1424. maskset = this.data('_inputmask')['maskset'];
  1425. opts = this.data('_inputmask')['opts'];
  1426. return maskScope(maskset, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split('') });
  1427. case "getmetadata": //return mask metadata if exists
  1428. if (this.data('_inputmask')) {
  1429. maskset = this.data('_inputmask')['maskset'];
  1430. return maskset['metadata'];
  1431. }
  1432. else return undefined;
  1433. default:
  1434. //check if the fn is an alias
  1435. if (!resolveAlias(fn, options, opts)) {
  1436. //maybe fn is a mask so we try
  1437. //set mask
  1438. opts.mask = fn;
  1439. }
  1440. maskset = generateMaskSet(opts);
  1441. if (maskset == undefined) { return this; }
  1442. return this.each(function () {
  1443. maskScope($.extend(true, {}, maskset), opts, { "action": "mask", "el": this });
  1444. });
  1445. break;
  1446. }
  1447. } else if (typeof fn == "object") {
  1448. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1449. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1450. maskset = generateMaskSet(opts);
  1451. if (maskset == undefined) { return this; }
  1452. return this.each(function () {
  1453. maskScope($.extend(true, {}, maskset), opts, { "action": "mask", "el": this });
  1454. });
  1455. } else if (fn == undefined) {
  1456. //look for data-inputmask atribute - the attribute should only contain optipns
  1457. return this.each(function () {
  1458. var attrOptions = $(this).attr("data-inputmask");
  1459. if (attrOptions && attrOptions != "") {
  1460. try {
  1461. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1462. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1463. $.extend(true, dataoptions, options);
  1464. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1465. resolveAlias(opts.alias, dataoptions, opts);
  1466. opts.alias = undefined;
  1467. $(this).inputmask(opts);
  1468. } catch (ex) { } //need a more relax parseJSON
  1469. }
  1470. });
  1471. }
  1472. };
  1473. }
  1474. })(jQuery);