jquery.inputmask.js 121 KB

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