jquery.inputmask.js 117 KB

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