jquery.inputmask.js 129 KB

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