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