jquery.inputmask.js 97 KB

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