jquery.inputmask.js 115 KB

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