jquery.inputmask.js 111 KB

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