jquery.inputmask.js 121 KB

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