jquery.inputmask.js 97 KB

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