jquery.inputmask.js 101 KB

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