jquery.inputmask.js 94 KB

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