jquery.inputmask.js 95 KB

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