jquery.inputmask.js 130 KB

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