jquery.inputmask.js 96 KB

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