jquery.inputmask.js 114 KB

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