jquery.inputmask.js 102 KB

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