jquery.inputmask.js 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  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. eventName = 'on' + eventName,
  14. isSupported = (eventName in el);
  15. if (!isSupported) {
  16. el.setAttribute(eventName, 'return;');
  17. isSupported = typeof el[eventName] == 'function';
  18. }
  19. el = null;
  20. return isSupported;
  21. }
  22. function resolveAlias(aliasStr, options, opts) {
  23. var aliasDefinition = opts.aliases[aliasStr];
  24. if (aliasDefinition) {
  25. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  26. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  27. $.extend(true, opts, options); //reapply extra given options
  28. return true;
  29. }
  30. return false;
  31. }
  32. function generateMaskSet(opts) {
  33. var ms = [];
  34. function analyseMask(mask) {
  35. var tokenizer = /(?:[?*+]|\{[0-9]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  36. escaped = false;
  37. function maskToken(isGroup, isOptional, isQuantifier) {
  38. this.matches = [];
  39. this.isGroup = isGroup || false;
  40. this.isOptional = isOptional || false;
  41. this.isQuantifier = isQuantifier || false;
  42. this.quantifier = { min: 1, max: 1 };
  43. };
  44. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
  45. function insertTestDefinition(mtoken, element, position) {
  46. var maskdef = opts.definitions[element];
  47. position = position != undefined ? position : mtoken.matches.length;
  48. if (maskdef && !escaped) {
  49. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  50. for (var i = 1; i < maskdef.cardinality; i++) {
  51. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  52. 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, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  53. }
  54. 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, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  55. } else {
  56. mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, casing: null, def: element });
  57. escaped = false;
  58. }
  59. }
  60. var currentToken = new maskToken(),
  61. match, m, openenings = [], maskTokens = [];
  62. while (match = tokenizer.exec(mask)) {
  63. m = match[0];
  64. switch (m.charAt(0)) {
  65. case opts.optionalmarker.end:
  66. // optional closing
  67. case opts.groupmarker.end:
  68. // Group closing
  69. var openingToken = openenings.pop();
  70. if (openenings.length > 0) {
  71. openenings[openenings.length - 1]["matches"].push(openingToken);
  72. } else {
  73. currentToken.matches.push(openingToken);
  74. }
  75. break;
  76. case opts.optionalmarker.start:
  77. // optional opening
  78. openenings.push(new maskToken(false, true));
  79. break;
  80. case opts.groupmarker.start:
  81. // Group opening
  82. openenings.push(new maskToken(true));
  83. break;
  84. case opts.quantifiermarker.start:
  85. //Quantifier
  86. var quantifier = new maskToken(false, false, true);
  87. m = m.replace(/[{}]/g, "");
  88. var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  89. quantifier.quantifier = { min: mq0, max: mq1 };
  90. if (mq1 == "*" || mq1 == "+") opts.greedy = false;
  91. if (openenings.length > 0) {
  92. var matches = openenings[openenings.length - 1]["matches"];
  93. var match = matches.pop();
  94. if (!match["isGroup"]) {
  95. var groupToken = new maskToken(true);
  96. groupToken.matches.push(match);
  97. match = groupToken;
  98. }
  99. matches.push(match);
  100. matches.push(quantifier);
  101. } else {
  102. var match = currentToken.matches.pop();
  103. if (!match["isGroup"]) {
  104. var groupToken = new maskToken(true);
  105. groupToken.matches.push(match);
  106. match = groupToken;
  107. }
  108. currentToken.matches.push(match);
  109. currentToken.matches.push(quantifier);
  110. }
  111. break;
  112. case opts.escapeChar:
  113. escaped = true;
  114. break;
  115. default:
  116. if (openenings.length > 0) {
  117. insertTestDefinition(openenings[openenings.length - 1], m);
  118. } else {
  119. if (currentToken.matches.length > 0) {
  120. var lastMatch = currentToken.matches[currentToken.matches.length - 1];
  121. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  122. lastMatch.isGroup = false;
  123. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  124. insertTestDefinition(lastMatch, opts.groupmarker.end);
  125. }
  126. }
  127. insertTestDefinition(currentToken, m);
  128. }
  129. }
  130. }
  131. if (currentToken.matches.length > 0)
  132. maskTokens.push(currentToken);
  133. //console.log(JSON.stringify(maskTokens));
  134. return maskTokens;
  135. }
  136. function generateMask(mask, metadata) {
  137. if (opts.numericInput) { //TODO FIXME for dynamic masks
  138. mask = mask.split('').reverse().join('');
  139. }
  140. if (mask == undefined || mask == "")
  141. return undefined;
  142. else {
  143. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  144. var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
  145. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  146. }
  147. if ($.inputmask.masksCache[mask] == undefined) {
  148. $.inputmask.masksCache[mask] = {
  149. "mask": mask,
  150. "maskToken": analyseMask(mask),
  151. "validPositions": {},
  152. "_buffer": undefined,
  153. "buffer": undefined,
  154. "tests": {},
  155. "metadata": metadata
  156. };
  157. }
  158. return $.extend(true, {}, $.inputmask.masksCache[mask]);
  159. }
  160. }
  161. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  162. opts.mask = opts.mask.call(this, opts);
  163. }
  164. if ($.isArray(opts.mask)) {
  165. $.each(opts.mask, function (ndx, msk) {
  166. if (msk["mask"] != undefined) {
  167. ms.push(generateMask(msk["mask"].toString(), msk));
  168. } else {
  169. ms.push(generateMask(msk.toString()));
  170. }
  171. });
  172. } else {
  173. if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  174. opts.placeholder = "";
  175. } //hide placeholder with single non-greedy mask
  176. if (opts.mask["mask"] != undefined) {
  177. ms = generateMask(opts.mask["mask"].toString(), opts.mask);
  178. } else {
  179. ms = generateMask(opts.mask.toString());
  180. }
  181. }
  182. return ms;
  183. }
  184. var msie1x = typeof ScriptEngineMajorVersion === "function"
  185. ? ScriptEngineMajorVersion() //IE11 detection
  186. : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
  187. ua = navigator.userAgent,
  188. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  189. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  190. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  191. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  192. 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),
  193. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  194. //if (androidchrome) {
  195. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  196. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  197. // androidchrome32 = (version == 32);
  198. //}
  199. //masking scope
  200. //actionObj definition see below
  201. function maskScope(maskset, opts, actionObj) {
  202. var isRTL = false,
  203. valueOnFocus = getBuffer().join(''),
  204. $el,
  205. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  206. skipInputEvent = false, //skip when triggered from within inputmask
  207. ignorable = false,
  208. maxLength;
  209. //maskset helperfunctions
  210. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  211. minimalPos = minimalPos || 0;
  212. var maskTemplate = [], ndxIntlzr, pos = 0, test;
  213. do {
  214. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  215. var validPos = getMaskSet()['validPositions'][pos];
  216. test = validPos["match"];
  217. ndxIntlzr = validPos["locator"].slice();
  218. maskTemplate.push(test["fn"] == null ? test["def"] : (includeInput === true ? validPos["input"] : opts.placeholder.charAt(pos % opts.placeholder.length)));
  219. } else {
  220. var testPos = getTests(pos, false, ndxIntlzr, pos - 1);
  221. testPos = testPos[opts.greedy || minimalPos > pos ? 0 : (testPos.length - 1)];
  222. test = testPos["match"];
  223. ndxIntlzr = testPos["locator"].slice();
  224. maskTemplate.push(test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  225. }
  226. pos++;
  227. } while ((maxLength == undefined || (pos - 1 < maxLength && maxLength > -1)) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  228. maskTemplate.pop(); //drop the last one which is empty
  229. return maskTemplate;
  230. }
  231. function getMaskSet() {
  232. return maskset;
  233. }
  234. function resetMaskSet(soft) {
  235. var maskset = getMaskSet();
  236. maskset["buffer"] = undefined;
  237. maskset["tests"] = {};
  238. if (soft !== true) {
  239. maskset["_buffer"] = undefined;
  240. maskset["validPositions"] = {};
  241. maskset["p"] = -1;
  242. }
  243. }
  244. function getLastValidPosition(closestTo) { //TODO implement closest to
  245. var maskset = getMaskSet();
  246. var lastValidPosition = -1;
  247. for (var posNdx in maskset["validPositions"]) {
  248. var psNdx = parseInt(posNdx);
  249. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  250. }
  251. return lastValidPosition;
  252. }
  253. function setValidPosition(pos, validTest, strict, fromSetValid) {
  254. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  255. //reposition & revalidate others
  256. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]);
  257. for (var i = seekPrevious(getMaskLength()) ; i > pos && i >= 0; i--) {
  258. if (isMask(i)) {
  259. var j = seekPrevious(i);
  260. var t = getMaskSet()["validPositions"][j];
  261. if (t != undefined) {
  262. if (getTest(i).def == getTest(j).def && getMaskSet()["validPositions"][i] == undefined && isValid(i, t["input"], strict, true) !== false) {
  263. delete getMaskSet()["validPositions"][j];
  264. }
  265. }
  266. }
  267. }
  268. if (getMaskSet()["validPositions"][pos] == undefined) {
  269. getMaskSet()["validPositions"][pos] = validTest;
  270. } else {
  271. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  272. return false;
  273. }
  274. } else
  275. getMaskSet()["validPositions"][pos] = validTest;
  276. return true;
  277. }
  278. function stripValidPositions(start, end) {
  279. var i, ml, startPos = seekNext(start - 1);
  280. for (i = start; i < end; i++) { //clear selection
  281. delete getMaskSet()["validPositions"][i];
  282. }
  283. for (i = end, ml = getMaskLength() ; i < ml; i++) { //clear selection
  284. var t = getMaskSet()["validPositions"][i];
  285. var s = getMaskSet()["validPositions"][startPos];
  286. if (t != undefined && s == undefined) {
  287. if (getTest(startPos).def == t.match.def && isValid(startPos, t["input"], true) !== false) {
  288. delete getMaskSet()["validPositions"][i];
  289. }
  290. startPos = seekNext(startPos);
  291. }
  292. }
  293. resetMaskSet(true);
  294. }
  295. function getTest(pos) {
  296. if (getMaskSet()['validPositions'][pos]) {
  297. return getMaskSet()['validPositions'][pos]["match"];
  298. }
  299. return getTests(pos)[0]["match"];
  300. }
  301. function getTests(pos, disableCache, ndxIntlzr, tstPs) {
  302. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  303. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  304. function handleMatch(match, loopNdx, quantifierRecurse) {
  305. var currentPos = testPos;
  306. if (testPos == pos && match.matches == undefined) {
  307. matches.push({ "match": match, "locator": loopNdx.reverse() });
  308. return true;
  309. } else if (match.matches != undefined) {
  310. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  311. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  312. if (match) return true;
  313. } else if (match.isOptional) {
  314. var optionalToken = match;
  315. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  316. if (match) {
  317. var latestMatch = matches[matches.length - 1]["match"];
  318. var isFirstMatch = (optionalToken.matches.indexOf(latestMatch) == 0);
  319. if (isFirstMatch) {
  320. insertStop = true; //insert a stop for non greedy
  321. }
  322. //search for next possible match
  323. testPos = currentPos;
  324. }
  325. } else if (match.isQuantifier && quantifierRecurse !== true) {
  326. var qt = match;
  327. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  328. var tokenGroup = maskToken.matches[maskToken.matches.indexOf(qt) - 1];
  329. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  330. if (match) {
  331. //get latest match
  332. var latestMatch = matches[matches.length - 1]["match"];
  333. if (qndx > qt.quantifier.min - 1) { //mark optionality
  334. latestMatch.optionalQuantifier = true;
  335. }
  336. var isFirstMatch = (tokenGroup.matches.indexOf(latestMatch) == 0);
  337. if (isFirstMatch) { //search for next possible match
  338. if (qndx > qt.quantifier.min - 1) {
  339. insertStop = true;
  340. testPos = pos; //match the position after the group
  341. break; //stop quantifierloop
  342. } else return true;
  343. } else {
  344. return true;
  345. }
  346. }
  347. }
  348. } else {
  349. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  350. if (match)
  351. return true;
  352. }
  353. } else testPos++;
  354. }
  355. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  356. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  357. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  358. if (match && testPos == pos) {
  359. return match;
  360. } else if (testPos > pos) {
  361. break;
  362. }
  363. }
  364. }
  365. }
  366. if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  367. return getMaskSet()['tests'][pos];
  368. }
  369. if (ndxIntlzr == undefined) {
  370. var previousPos = pos - 1, test;
  371. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  372. previousPos--;
  373. }
  374. if (test != undefined && previousPos > -1) {
  375. testPos = previousPos;
  376. ndxInitializer = test["locator"].slice();
  377. } else {
  378. previousPos = pos - 1;
  379. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  380. previousPos--;
  381. }
  382. if (test != undefined && previousPos > -1) {
  383. testPos = previousPos;
  384. ndxInitializer = test[0]["locator"].slice();
  385. }
  386. }
  387. }
  388. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  389. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  390. if ((match && testPos == pos) || testPos > pos) {
  391. break;
  392. }
  393. }
  394. if (matches.length == 0 || (insertStop && matches.length < 2))
  395. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  396. getMaskSet()['tests'][pos] = matches;
  397. //console.log(pos + " - " + JSON.stringify(matches));
  398. return matches;
  399. }
  400. function getBufferTemplate() {
  401. if (getMaskSet()['_buffer'] == undefined) {
  402. //generate template
  403. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  404. }
  405. return getMaskSet()['_buffer'];
  406. }
  407. function getBuffer() {
  408. if (getMaskSet()['buffer'] == undefined) {
  409. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  410. }
  411. return getMaskSet()['buffer'];
  412. }
  413. function refreshFromBuffer(start, end) {
  414. var buffer = getBuffer();
  415. for (var i = start; i < end; i++) {
  416. if (buffer[i] != getPlaceholder(i)) {
  417. var ltst = getTests(i, false)[0];
  418. setValidPosition(i, $.extend({}, ltst, { "input": casing(buffer[i], ltst["match"]) }), true);
  419. }
  420. }
  421. }
  422. function casing(elem, test) {
  423. switch (test.casing) {
  424. case "upper":
  425. elem = elem.toUpperCase();
  426. break;
  427. case "lower":
  428. elem = elem.toLowerCase();
  429. break;
  430. }
  431. return elem;
  432. }
  433. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  434. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  435. function _isValid(position, c, strict, fromSetValid) {
  436. var rslt = false;
  437. $.each(getTests(position, !strict), function (ndx, tst) {
  438. var test = tst["match"];
  439. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  440. for (var i = test.cardinality; i > loopend; i--) {
  441. chrs += getBufferElement(position - (i - 1));
  442. }
  443. if (c) {
  444. chrs += c;
  445. }
  446. //return is false or a json object => { pos: ??, c: ??} or true
  447. rslt = test.fn != null ?
  448. test.fn.test(chrs, buffer, position, strict, opts)
  449. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  450. { c: test["def"], pos: position }
  451. : false;
  452. if (rslt !== false) {
  453. var elem = rslt.c != undefined ? rslt.c : c;
  454. elem = elem == opts.skipOptionalPartCharacter ? test["def"] : elem;
  455. var validatedPos = position;
  456. if (rslt["refreshFromBuffer"] === true) {
  457. strict = true;
  458. validatedPos = rslt["pos"];
  459. getMaskSet()["validPositions"] = {};
  460. refreshFromBuffer(0, getBuffer().length);
  461. } else if (rslt !== true && rslt["pos"] != position) { //their is a position offset
  462. setValidPosition(position, $.extend({}, tst, { "input": casing(buffer[position], test) }), strict);
  463. validatedPos = rslt["pos"];
  464. refreshFromBuffer(position + 1, validatedPos);
  465. tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO
  466. }
  467. if (ndx > 0) {
  468. resetMaskSet(true);
  469. }
  470. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), strict, fromSetValid))
  471. rslt = false;
  472. return false; //break from $.each
  473. }
  474. });
  475. return rslt;
  476. }
  477. var maskPos = pos;
  478. var result = _isValid(maskPos, c, strict, fromSetValid);
  479. if (!strict && (opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && result === false && !isMask(maskPos)) { //does the input match on a further position?
  480. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  481. result = _isValid(nPos, c, strict, fromSetValid);
  482. if (result !== false) {
  483. maskPos = nPos;
  484. break;
  485. }
  486. }
  487. }
  488. if (result === true) result = { "pos": maskPos };
  489. return result;
  490. }
  491. function isMask(pos) {
  492. var test = getTest(pos);
  493. return test.fn != null ? test.fn : false;
  494. }
  495. function getMaskLength() {
  496. var maskLength; maxLength = $el.prop('maxLength');
  497. if (opts.greedy == false) { //TODO FIXME OPTIMIZE ME
  498. var lvp = getLastValidPosition() + 1,
  499. test = getTest(lvp);
  500. while (!(test.fn == null && test.def == "")) { //determine last possible position
  501. test = getTest(++lvp);
  502. if (test.optionality !== true) {
  503. var tests = getTests(lvp);
  504. test = tests[tests.length - 1]["match"];
  505. }
  506. }
  507. maskLength = getMaskTemplate(true, lvp).length;
  508. getMaskSet()["tests"] = {}; //cleanup tests
  509. } else
  510. maskLength = getBuffer().length;
  511. return maxLength == undefined || (maskLength < maxLength && maxLength > -1) /* FF sets no defined max length to -1 */ ? maskLength : maxLength;
  512. }
  513. function seekNext(pos) {
  514. var maskL = getMaskLength();
  515. if (pos >= maskL) return maskL;
  516. var position = pos;
  517. while (++position < maskL && !isMask(position)) {
  518. }
  519. return position;
  520. }
  521. function seekPrevious(pos) {
  522. var position = pos;
  523. if (position <= 0) return 0;
  524. while (--position > 0 && !isMask(position)) {
  525. }
  526. ;
  527. return position;
  528. }
  529. function getBufferElement(position) {
  530. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  531. }
  532. function writeBuffer(input, buffer, caretPos) {
  533. input._valueSet(buffer.join(''));
  534. if (caretPos != undefined) {
  535. caret(input, caretPos);
  536. }
  537. }
  538. function getPlaceholder(pos) {
  539. var test = getTest(pos);
  540. return test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length);
  541. }
  542. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  543. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  544. resetMaskSet();
  545. if (writeOut) input._valueSet(""); //initial clear
  546. $.each(inputValue, function (ndx, charCode) {
  547. if (intelliCheck === true) {
  548. var p = getMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p),
  549. pos = lvp == -1 ? ndx : seekNext(lvp);
  550. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
  551. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  552. }
  553. } else {
  554. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  555. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  556. }
  557. });
  558. }
  559. function escapeRegex(str) {
  560. return $.inputmask.escapeRegex.call(this, str);
  561. }
  562. function truncateInput(inputValue) {
  563. return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
  564. }
  565. function clearOptionalTail(input) {
  566. var buffer = getBuffer(), tmpBuffer = buffer.slice(), pos;
  567. for (pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  568. var test = getTest(pos);
  569. if ((test.optionality || test.optionalQuantifier) && tmpBuffer[pos] == getPlaceholder(pos)) {
  570. tmpBuffer.pop();
  571. } else break;
  572. }
  573. writeBuffer(input, tmpBuffer);
  574. }
  575. function unmaskedvalue($input, skipDatepickerCheck) {
  576. if ($input.data('_inputmask') && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  577. var umValue = $.map(getBuffer(), function (element, index) {
  578. return isMask(index) && isValid(index, element, true) ? element : null;
  579. });
  580. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  581. var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
  582. return $.isFunction(opts.onUnMask) ? opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) : unmaskedValue;
  583. } else {
  584. return $input[0]._valueGet();
  585. }
  586. }
  587. function TranslatePosition(pos) {
  588. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  589. var bffrLght = getBuffer().length;
  590. pos = bffrLght - pos;
  591. }
  592. return pos;
  593. }
  594. function caret(input, begin, end) {
  595. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  596. if (typeof begin == 'number') {
  597. begin = TranslatePosition(begin);
  598. end = TranslatePosition(end);
  599. end = (typeof end == 'number') ? end : begin;
  600. //store caret for multi scope
  601. var data = $(input).data('_inputmask') || {};
  602. data["caret"] = { "begin": begin, "end": end };
  603. $(input).data('_inputmask', data);
  604. if (!$(npt).is(':visible')) {
  605. return;
  606. }
  607. npt.scrollLeft = npt.scrollWidth;
  608. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  609. if (npt.setSelectionRange) {
  610. npt.selectionStart = begin;
  611. npt.selectionEnd = end;
  612. } else if (npt.createTextRange) {
  613. range = npt.createTextRange();
  614. range.collapse(true);
  615. range.moveEnd('character', end);
  616. range.moveStart('character', begin);
  617. range.select();
  618. }
  619. } else {
  620. if (!$(input).is(':visible')) {
  621. var data = $(input).data('_inputmask');
  622. return data["caret"] || { begin: 0, end: 0 };
  623. }
  624. if (npt.setSelectionRange) {
  625. begin = npt.selectionStart;
  626. end = npt.selectionEnd;
  627. } else if (document.selection && document.selection.createRange) {
  628. range = document.selection.createRange();
  629. begin = 0 - range.duplicate().moveStart('character', -100000);
  630. end = begin + range.text.length;
  631. }
  632. begin = TranslatePosition(begin);
  633. end = TranslatePosition(end);
  634. return { "begin": begin, "end": end };
  635. }
  636. }
  637. function isComplete(buffer) { //return true / false / undefined (repeat *)
  638. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  639. if (opts.repeat == "*") return undefined;
  640. var complete = false,
  641. aml = seekPrevious(getMaskLength());
  642. if (getLastValidPosition() == aml) {
  643. complete = true;
  644. for (var i = 0; i <= aml; i++) {
  645. var mask = isMask(i);
  646. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  647. complete = false;
  648. break;
  649. }
  650. }
  651. }
  652. return complete;
  653. }
  654. function isSelection(begin, end) {
  655. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  656. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  657. }
  658. function installEventRuler(npt) {
  659. var events = $._data(npt).events;
  660. $.each(events, function (eventType, eventHandlers) {
  661. $.each(eventHandlers, function (ndx, eventHandler) {
  662. if (eventHandler.namespace == "inputmask") {
  663. if (eventHandler.type != "setvalue") {
  664. var handler = eventHandler.handler;
  665. eventHandler.handler = function (e) {
  666. if (this.readOnly || this.disabled)
  667. e.preventDefault;
  668. else
  669. return handler.apply(this, arguments);
  670. };
  671. }
  672. }
  673. });
  674. });
  675. }
  676. function patchValueProperty(npt) {
  677. function PatchValhook(type) {
  678. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  679. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  680. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  681. elem.value = value;
  682. return elem;
  683. };
  684. $.valHooks[type] = {
  685. get: function (elem) {
  686. var $elem = $(elem);
  687. if ($elem.data('_inputmask')) {
  688. if ($elem.data('_inputmask')['opts'].autoUnmask)
  689. return $elem.inputmask('unmaskedvalue');
  690. else {
  691. var result = valueGet(elem),
  692. inputData = $elem.data('_inputmask'), maskset = inputData['maskset'],
  693. bufferTemplate = maskset['_buffer'];
  694. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  695. return result != bufferTemplate ? result : '';
  696. }
  697. } else return valueGet(elem);
  698. },
  699. set: function (elem, value) {
  700. var $elem = $(elem);
  701. var result = valueSet(elem, value);
  702. if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
  703. return result;
  704. },
  705. inputmaskpatch: true
  706. };
  707. }
  708. }
  709. var valueProperty;
  710. if (Object.getOwnPropertyDescriptor)
  711. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  712. if (valueProperty && valueProperty.get) {
  713. if (!npt._valueGet) {
  714. var valueGet = valueProperty.get;
  715. var valueSet = valueProperty.set;
  716. npt._valueGet = function () {
  717. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  718. };
  719. npt._valueSet = function (value) {
  720. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  721. };
  722. Object.defineProperty(npt, "value", {
  723. get: function () {
  724. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  725. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  726. },
  727. set: function (value) {
  728. valueSet.call(this, value);
  729. $(this).triggerHandler('setvalue.inputmask');
  730. }
  731. });
  732. }
  733. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  734. if (!npt._valueGet) {
  735. var valueGet = npt.__lookupGetter__("value");
  736. var valueSet = npt.__lookupSetter__("value");
  737. npt._valueGet = function () {
  738. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  739. };
  740. npt._valueSet = function (value) {
  741. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  742. };
  743. npt.__defineGetter__("value", function () {
  744. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  745. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  746. });
  747. npt.__defineSetter__("value", function (value) {
  748. valueSet.call(this, value);
  749. $(this).triggerHandler('setvalue.inputmask');
  750. });
  751. }
  752. } else {
  753. if (!npt._valueGet) {
  754. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  755. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  756. }
  757. PatchValhook(npt.type);
  758. }
  759. }
  760. function HandleRemove(input, k, pos) {
  761. if (opts.numericInput || isRTL) {
  762. switch (k) {
  763. case opts.keyCode.BACKSPACE:
  764. k = opts.keyCode.DELETE;
  765. break;
  766. case opts.keyCode.DELETE:
  767. k = opts.keyCode.BACKSPACE;
  768. break;
  769. }
  770. if (isRTL) {
  771. var pend = pos.end;
  772. pos.end = pos.begin;
  773. pos.begin = pend;
  774. }
  775. }
  776. if (pos.begin == pos.end) {
  777. var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
  778. if (opts.isNumeric && opts.radixPoint != "" && getBuffer()[posBegin] == opts.radixPoint) {
  779. pos.begin = (getBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
  780. pos.end = pos.begin;
  781. }
  782. if (k == opts.keyCode.BACKSPACE)
  783. pos.begin = seekPrevious(pos.begin);
  784. else if (k == opts.keyCode.DELETE)
  785. pos.end++;
  786. } else if (pos.end - pos.begin == 1 && !opts.insertMode) {
  787. if (k == opts.keyCode.BACKSPACE)
  788. pos.begin--;
  789. }
  790. stripValidPositions(pos.begin, pos.end);
  791. var firstMaskPos = seekNext(-1);
  792. if (getLastValidPosition() < firstMaskPos) {
  793. getMaskSet()["p"] = firstMaskPos;
  794. } else {
  795. getMaskSet()["p"] = pos.begin;
  796. }
  797. }
  798. function keydownEvent(e) {
  799. //Safari 5.1.x - modal dialog fires keypress twice workaround
  800. skipKeyPressEvent = false;
  801. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  802. //backspace, delete, and escape get special treatment
  803. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  804. e.preventDefault(); //stop default action but allow propagation
  805. if (k == 88) valueOnFocus = getBuffer().join('');
  806. HandleRemove(input, k, pos);
  807. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  808. if (input._valueGet() == getBufferTemplate().join(''))
  809. $input.trigger('cleared');
  810. if (opts.showTooltip) { //update tooltip
  811. $input.prop("title", getMaskSet()["mask"]);
  812. }
  813. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  814. setTimeout(function () {
  815. var caretPos = seekNext(getLastValidPosition());
  816. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  817. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  818. }, 0);
  819. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  820. caret(input, 0, e.shiftKey ? pos.begin : 0);
  821. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  822. checkVal(input, true, false, valueOnFocus.split(''));
  823. $input.click();
  824. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  825. opts.insertMode = !opts.insertMode;
  826. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  827. } else if (opts.insertMode == false && !e.shiftKey) {
  828. if (k == opts.keyCode.RIGHT) {
  829. setTimeout(function () {
  830. var caretPos = caret(input);
  831. caret(input, caretPos.begin);
  832. }, 0);
  833. } else if (k == opts.keyCode.LEFT) {
  834. setTimeout(function () {
  835. var caretPos = caret(input);
  836. caret(input, caretPos.begin - 1);
  837. }, 0);
  838. }
  839. }
  840. var currentCaretPos = caret(input);
  841. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), opts);
  842. if (keydownResult && keydownResult["refreshFromBuffer"] === true) { //extra stuff to execute on keydown
  843. getMaskSet()["validPositions"] = {};
  844. refreshFromBuffer(0, getBuffer().length);
  845. caret(input, currentCaretPos.begin, currentCaretPos.end);
  846. }
  847. ignorable = $.inArray(k, opts.ignorables) != -1;
  848. }
  849. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  850. //Safari 5.1.x - modal dialog fires keypress twice workaround
  851. if (k == undefined && skipKeyPressEvent) return false;
  852. skipKeyPressEvent = true;
  853. var input = this, $input = $(input);
  854. e = e || window.event;
  855. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  856. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  857. return true;
  858. } else {
  859. if (k) {
  860. //special treat the decimal separator
  861. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  862. var pos, forwardPosition, c = String.fromCharCode(k);
  863. if (checkval) {
  864. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  865. pos = { begin: pcaret, end: pcaret };
  866. } else {
  867. pos = caret(input);
  868. }
  869. //should we clear a possible selection??
  870. var isSlctn = isSelection(pos.begin, pos.end);
  871. if (isSlctn) {
  872. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  873. HandleRemove(input, opts.keyCode.DELETE, pos);
  874. if (!opts.insertMode) { //preserve some space
  875. opts.insertMode = !opts.insertMode;
  876. setValidPosition(pos.begin, undefined, strict);
  877. opts.insertMode = !opts.insertMode;
  878. }
  879. }
  880. var radixPosition = getBuffer().join('').indexOf(opts.radixPoint);
  881. if (opts.isNumeric && checkval !== true && radixPosition != -1) {
  882. if (opts.greedy && pos.begin <= radixPosition) {
  883. pos.begin = seekPrevious(pos.begin);
  884. pos.end = pos.begin;
  885. } else if (c == opts.radixPoint) {
  886. pos.begin = radixPosition;
  887. pos.end = pos.begin;
  888. }
  889. }
  890. getMaskSet()["writeOutBuffer"] = true;
  891. var p = pos.begin;
  892. var valResult = isValid(p, c, strict);
  893. if (valResult !== false) {
  894. if (valResult !== true) {
  895. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  896. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  897. }
  898. resetMaskSet(true);
  899. forwardPosition = seekNext(p);
  900. getMaskSet()["p"] = forwardPosition; //needed for checkval
  901. }
  902. if (writeOut !== false) {
  903. var self = this;
  904. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  905. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  906. var buffer = getBuffer();
  907. var newCaretPosition;
  908. if (checkval) {
  909. newCaretPosition = undefined;
  910. } else if (opts.numericInput) {
  911. if (p > radixPosition) {
  912. newCaretPosition = seekPrevious(forwardPosition);
  913. } else if (c == opts.radixPoint) {
  914. newCaretPosition = forwardPosition - 1;
  915. } else newCaretPosition = seekPrevious(forwardPosition - 1);
  916. } else {
  917. newCaretPosition = forwardPosition;
  918. }
  919. writeBuffer(input, buffer, newCaretPosition);
  920. if (checkval !== true) {
  921. setTimeout(function () { //timeout needed for IE
  922. if (isComplete(buffer) === true)
  923. $input.trigger("complete");
  924. skipInputEvent = true;
  925. $input.trigger("input");
  926. }, 0);
  927. }
  928. } else if (isSlctn) {
  929. getMaskSet()["buffer"] = undefined;
  930. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  931. }
  932. } else if (isSlctn) {
  933. getMaskSet()["buffer"] = undefined;
  934. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  935. }
  936. if (opts.showTooltip) { //update tooltip
  937. $input.prop("title", getMaskSet()["mask"]);
  938. }
  939. //needed for IE8 and below
  940. if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false;
  941. }
  942. }
  943. }
  944. function keyupEvent(e) {
  945. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  946. var keyupResult = opts.onKeyUp.call(this, e, buffer, opts);
  947. if (keyupResult && keyupResult["refreshFromBuffer"] === true) {
  948. getMaskSet()["validPositions"] = {};
  949. refreshFromBuffer(0, getBuffer().length);
  950. }
  951. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  952. if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  953. resetMaskSet();
  954. buffer = getBuffer();
  955. writeBuffer(input, buffer);
  956. caret(input, 0);
  957. valueOnFocus = getBuffer().join('');
  958. } else {
  959. writeBuffer(input, buffer);
  960. if (buffer.join('') == getBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) {
  961. caret(input, TranslatePosition(0));
  962. $input.click();
  963. } else
  964. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  965. }
  966. }
  967. }
  968. function pasteEvent(e) {
  969. if (skipInputEvent === true && e.type == "input") {
  970. skipInputEvent = false;
  971. return true;
  972. }
  973. var input = this, $input = $(input);
  974. //paste event for IE8 and lower I guess ;-)
  975. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  976. return true;
  977. }
  978. setTimeout(function () {
  979. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, input._valueGet(), opts) : input._valueGet();
  980. checkVal(input, false, false, pasteValue.split(''), true);
  981. writeBuffer(input, getBuffer());
  982. if (isComplete(getBuffer()) === true)
  983. $input.trigger("complete");
  984. $input.click();
  985. }, 0);
  986. }
  987. function mobileInputEvent(e) {
  988. var input = this, $input = $(input);
  989. //backspace in chrome32 only fires input event - detect & treat
  990. var caretPos = caret(input),
  991. currentValue = input._valueGet();
  992. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  993. //correct caretposition for chrome
  994. if (caretPos.begin > currentValue.length) {
  995. caret(input, currentValue.length);
  996. caretPos = caret(input);
  997. }
  998. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  999. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1000. && !isMask(caretPos.begin)) {
  1001. e.keyCode = opts.keyCode.BACKSPACE;
  1002. keydownEvent.call(input, e);
  1003. } else { //nonnumerics don't fire keypress
  1004. checkVal(input, false, false, currentValue.split(''));
  1005. writeBuffer(input, getBuffer());
  1006. if (isComplete(getBuffer()) === true)
  1007. $input.trigger("complete");
  1008. $input.click();
  1009. }
  1010. e.preventDefault();
  1011. }
  1012. function mask(el) {
  1013. $el = $(el);
  1014. if ($el.is(":input")) {
  1015. //store tests & original buffer in the input element - used to get the unmasked value
  1016. $el.data('_inputmask', {
  1017. 'maskset': maskset,
  1018. 'opts': opts,
  1019. 'isRTL': false
  1020. });
  1021. //show tooltip
  1022. if (opts.showTooltip) {
  1023. $el.prop("title", getMaskSet()["mask"]);
  1024. }
  1025. patchValueProperty(el);
  1026. if (opts.numericInput) opts.isNumeric = opts.numericInput;
  1027. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1028. $el.css("text-align", "right");
  1029. if (el.dir == "rtl" || opts.numericInput) {
  1030. el.dir = "ltr";
  1031. $el.removeAttr("dir");
  1032. var inputData = $el.data('_inputmask');
  1033. inputData['isRTL'] = true;
  1034. $el.data('_inputmask', inputData);
  1035. isRTL = true;
  1036. }
  1037. //unbind all events - to make sure that no other mask will interfere when re-masking
  1038. $el.unbind(".inputmask");
  1039. $el.removeClass('focus.inputmask');
  1040. //bind events
  1041. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1042. if (valueOnFocus != getBuffer().join('')) {
  1043. $el.change();
  1044. }
  1045. }).bind('reset', function () {
  1046. setTimeout(function () {
  1047. $el.trigger("setvalue");
  1048. }, 0);
  1049. });
  1050. $el.bind("mouseenter.inputmask", function () {
  1051. var $input = $(this), input = this;
  1052. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  1053. if (input._valueGet() != getBuffer().join('')) {
  1054. writeBuffer(input, getBuffer());
  1055. }
  1056. }
  1057. }).bind("blur.inputmask", function () {
  1058. var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getBuffer();
  1059. $input.removeClass('focus.inputmask');
  1060. if (valueOnFocus != getBuffer().join('')) {
  1061. $input.change();
  1062. }
  1063. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1064. if (nptValue == getBufferTemplate().join(''))
  1065. input._valueSet('');
  1066. else { //clearout optional tail of the mask
  1067. clearOptionalTail(input);
  1068. }
  1069. }
  1070. if (isComplete(buffer) === false) {
  1071. $input.trigger("incomplete");
  1072. if (opts.clearIncomplete) {
  1073. resetMaskSet();
  1074. if (opts.clearMaskOnLostFocus)
  1075. input._valueSet('');
  1076. else {
  1077. buffer = getBufferTemplate().slice();
  1078. writeBuffer(input, buffer);
  1079. }
  1080. }
  1081. }
  1082. }).bind("focus.inputmask", function () {
  1083. var $input = $(this), input = this, nptValue = input._valueGet();
  1084. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1085. if (input._valueGet() != getBuffer().join('')) {
  1086. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1087. }
  1088. }
  1089. $input.addClass('focus.inputmask');
  1090. valueOnFocus = getBuffer().join('');
  1091. }).bind("mouseleave.inputmask", function () {
  1092. var $input = $(this), input = this;
  1093. if (opts.clearMaskOnLostFocus) {
  1094. if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1095. if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
  1096. input._valueSet('');
  1097. else { //clearout optional tail of the mask
  1098. clearOptionalTail(input);
  1099. }
  1100. }
  1101. }
  1102. }).bind("click.inputmask", function () {
  1103. var input = this;
  1104. setTimeout(function () {
  1105. var selectedCaret = caret(input), buffer = getBuffer();
  1106. if (selectedCaret.begin == selectedCaret.end) {
  1107. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1108. lvp = getLastValidPosition(clickPosition),
  1109. lastPosition;
  1110. if (opts.isNumeric) {
  1111. lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
  1112. (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
  1113. seekNext(lvp);
  1114. } else {
  1115. lastPosition = seekNext(lvp);
  1116. }
  1117. if (clickPosition < lastPosition) {
  1118. if (isMask(clickPosition))
  1119. caret(input, clickPosition);
  1120. else caret(input, seekNext(clickPosition));
  1121. } else
  1122. caret(input, lastPosition);
  1123. }
  1124. }, 0);
  1125. }).bind('dblclick.inputmask', function () {
  1126. var input = this;
  1127. setTimeout(function () {
  1128. caret(input, 0, seekNext(getLastValidPosition()));
  1129. }, 0);
  1130. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1131. ).bind('setvalue.inputmask', function () {
  1132. var input = this;
  1133. checkVal(input, true);
  1134. valueOnFocus = getBuffer().join('');
  1135. if (input._valueGet() == getBufferTemplate().join(''))
  1136. input._valueSet('');
  1137. }).bind('complete.inputmask', opts.oncomplete
  1138. ).bind('incomplete.inputmask', opts.onincomplete
  1139. ).bind('cleared.inputmask', opts.oncleared);
  1140. $el.bind("keydown.inputmask", keydownEvent
  1141. ).bind("keypress.inputmask", keypressEvent
  1142. ).bind("keyup.inputmask", keyupEvent);
  1143. // as the other inputevents aren't reliable for the moment we only base on the input event
  1144. // needs follow-up
  1145. if (android || androidfirefox || androidchrome || kindle) {
  1146. $el.attr("autocomplete", "off")
  1147. .attr("autocorrect", "off")
  1148. .attr("autocapitalize", "off")
  1149. .attr("spellcheck", false);
  1150. if (androidfirefox || kindle) {
  1151. $el.unbind("keydown.inputmask", keydownEvent
  1152. ).unbind("keypress.inputmask", keypressEvent
  1153. ).unbind("keyup.inputmask", keyupEvent);
  1154. if (PasteEventType == "input") {
  1155. $el.unbind(PasteEventType + ".inputmask");
  1156. }
  1157. $el.bind("input.inputmask", mobileInputEvent);
  1158. }
  1159. }
  1160. if (msie1x)
  1161. $el.bind("input.inputmask", pasteEvent);
  1162. //apply mask
  1163. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1164. checkVal(el, true, false, initialValue.split(''), true);
  1165. valueOnFocus = getBuffer().join('');
  1166. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1167. var activeElement;
  1168. try {
  1169. activeElement = document.activeElement;
  1170. } catch (e) {
  1171. }
  1172. if (activeElement === el) { //position the caret when in focus
  1173. $el.addClass('focus.inputmask');
  1174. caret(el, seekNext(getLastValidPosition()));
  1175. } else if (opts.clearMaskOnLostFocus) {
  1176. if (getBuffer().join('') == getBufferTemplate().join('')) {
  1177. el._valueSet('');
  1178. } else {
  1179. clearOptionalTail(el);
  1180. }
  1181. } else {
  1182. writeBuffer(el, getBuffer());
  1183. }
  1184. installEventRuler(el);
  1185. }
  1186. }
  1187. //action object
  1188. if (actionObj != undefined) {
  1189. switch (actionObj["action"]) {
  1190. case "isComplete":
  1191. return isComplete(actionObj["buffer"]);
  1192. case "unmaskedvalue":
  1193. $el = actionObj["$input"];
  1194. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1195. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1196. case "mask":
  1197. mask(actionObj["el"]);
  1198. break;
  1199. case "format":
  1200. $el = $({});
  1201. $el.data('_inputmask', {
  1202. 'maskset': maskset,
  1203. 'opts': opts,
  1204. 'isRTL': opts.numericInput
  1205. });
  1206. if (opts.numericInput) {
  1207. opts.isNumeric = opts.numericInput;
  1208. isRTL = true;
  1209. }
  1210. var valueBuffer = actionObj["value"].split('');
  1211. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer, true);
  1212. return isRTL ? getBuffer().reverse().join('') : getBuffer().join('');
  1213. case "isValid":
  1214. $el = $({});
  1215. $el.data('_inputmask', {
  1216. 'maskset': maskset,
  1217. 'opts': opts,
  1218. 'isRTL': opts.numericInput
  1219. });
  1220. if (opts.numericInput) {
  1221. opts.isNumeric = opts.numericInput;
  1222. isRTL = true;
  1223. }
  1224. var valueBuffer = actionObj["value"].split('');
  1225. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1226. return isComplete(getBuffer());
  1227. }
  1228. }
  1229. };
  1230. function multiMaskScope(el, masksets, opts) {
  1231. function caret(input, begin, end) {
  1232. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  1233. if (typeof begin == 'number') {
  1234. end = (typeof end == 'number') ? end : begin;
  1235. //store caret for multi scope
  1236. var data = $(input).data('_inputmask') || {};
  1237. data["caret"] = { "begin": begin, "end": end };
  1238. $(input).data('_inputmask', data);
  1239. if (!$(npt).is(':visible')) {
  1240. return;
  1241. }
  1242. npt.scrollLeft = npt.scrollWidth;
  1243. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  1244. if (npt.setSelectionRange) {
  1245. npt.selectionStart = begin;
  1246. npt.selectionEnd = end;
  1247. } else if (npt.createTextRange) {
  1248. range = npt.createTextRange();
  1249. range.collapse(true);
  1250. range.moveEnd('character', end);
  1251. range.moveStart('character', begin);
  1252. range.select();
  1253. }
  1254. } else {
  1255. if (!$(input).is(':visible')) {
  1256. var data = $(input).data('_inputmask');
  1257. return data["caret"] || { begin: 0, end: 0 };
  1258. }
  1259. if (npt.setSelectionRange) {
  1260. begin = npt.selectionStart;
  1261. end = npt.selectionEnd;
  1262. } else if (document.selection && document.selection.createRange) {
  1263. range = document.selection.createRange();
  1264. begin = 0 - range.duplicate().moveStart('character', -100000);
  1265. end = begin + range.text.length;
  1266. }
  1267. return { "begin": begin, "end": end };
  1268. }
  1269. }
  1270. var activeMasksetIndex = 0, elmasks = $.map(masksets, function (msk, ndx) {
  1271. var elmask = $('<input type="text" />')[0];
  1272. maskScope($.extend(true, {}, msk), opts, { "action": "mask", "el": elmask });
  1273. return elmask;
  1274. });
  1275. function determineActiveMask(eventType, elmasks) {
  1276. if ($.isFunction(opts.determineActiveMasksetIndex)) activeMasksetIndex = opts.determineActiveMasksetIndex.call($el, eventType, elmasks);
  1277. $(el).val(elmasks[activeMasksetIndex]._valueGet());
  1278. if (["blur", "focus"].indexOf(eventType) == -1) {
  1279. caret(el, caret(elmasks[activeMasksetIndex]).begin);
  1280. }
  1281. }
  1282. $(el).bind("mouseenter blur focus mouseleave click dblclick " + PasteEventType + " dragdrop drop keydown keypress keypress", function (e) {
  1283. var caretPos, k;
  1284. if (e.type == "keydown") {
  1285. k = e.keyCode;
  1286. if (k == opts.keyCode.DOWN && activeMasksetIndex < elmasks.length) {
  1287. activeMasksetIndex++;
  1288. determineActiveMask(e.type, elmasks);
  1289. return false;
  1290. } else if (k == opts.keyCode.UP && activeMasksetIndex > 0) {
  1291. activeMasksetIndex--;
  1292. determineActiveMask(e.type, elmasks);
  1293. return false;
  1294. }
  1295. }
  1296. $.each(elmasks, function (ndx, lmnt) {
  1297. if (e.type == "keydown") {
  1298. k = e.keyCode;
  1299. if (k == opts.keyCode.RIGHT) {
  1300. caretPos = caret(el);
  1301. caret(lmnt, caretPos.begin + 1, caretPos.end + 1);
  1302. return;
  1303. } else if (k == opts.keyCode.LEFT) {
  1304. caretPos = caret(el);
  1305. caret(lmnt, caretPos.begin - 1, caretPos.end - 1);
  1306. return;
  1307. }
  1308. } else if (["click", "keydown", "keypress", "keyup"].indexOf(e.type) != -1) {
  1309. caretPos = caret(el);
  1310. caret(lmnt, caretPos.begin, caretPos.end);
  1311. }
  1312. setTimeout(function () {
  1313. $(lmnt).triggerHandler(e);
  1314. setTimeout(function () {
  1315. determineActiveMask(e.type, elmasks);
  1316. }, 0);
  1317. }, 0);
  1318. });
  1319. });
  1320. };
  1321. $.inputmask = {
  1322. //options default
  1323. defaults: {
  1324. placeholder: "_",
  1325. optionalmarker: { start: "[", end: "]" },
  1326. quantifiermarker: { start: "{", end: "}" },
  1327. groupmarker: { start: "(", end: ")" },
  1328. escapeChar: "\\",
  1329. mask: null,
  1330. oncomplete: $.noop, //executes when the mask is complete
  1331. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1332. oncleared: $.noop, //executes when the mask is cleared
  1333. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1334. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1335. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1336. clearMaskOnLostFocus: true,
  1337. insertMode: true, //insert the input or overwrite the input
  1338. clearIncomplete: false, //clear the incomplete input on blur
  1339. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1340. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  1341. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  1342. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1343. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1344. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1345. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1346. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1347. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1348. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1349. showTooltip: false, //show the activemask as tooltip
  1350. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1351. //numeric basic properties
  1352. isNumeric: false, //enable numeric features
  1353. radixPoint: "", //".", // | ","
  1354. skipRadixDance: false, //disable radixpoint caret positioning
  1355. rightAlignNumerics: true, //align numerics to the right
  1356. //numeric basic properties
  1357. definitions: {
  1358. '9': {
  1359. validator: "[0-9]",
  1360. cardinality: 1,
  1361. definitionSymbol: "*"
  1362. },
  1363. 'a': {
  1364. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1365. cardinality: 1,
  1366. definitionSymbol: "*"
  1367. },
  1368. '*': {
  1369. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1370. cardinality: 1
  1371. }
  1372. },
  1373. keyCode: {
  1374. 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,
  1375. 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
  1376. },
  1377. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1378. 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],
  1379. isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false
  1380. //multi-masks
  1381. determineActiveMasksetIndex: undefined //override determineActiveMasksetIndex - args => eventType, elmasks - return int
  1382. },
  1383. masksCache: {},
  1384. escapeRegex: function (str) {
  1385. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1386. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1387. },
  1388. format: function (value, options) {
  1389. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1390. resolveAlias(opts.alias, options, opts);
  1391. return maskScope(generateMaskSet(opts), opts, { "action": "format", "value": value });
  1392. },
  1393. isValid: function (value, options) {
  1394. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1395. resolveAlias(opts.alias, options, opts);
  1396. return maskScope(generateMaskSet(opts), opts, { "action": "isValid", "value": value });
  1397. }
  1398. };
  1399. $.fn.inputmask = function (fn, options) {
  1400. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1401. maskset;
  1402. if (typeof fn === "string") {
  1403. switch (fn) {
  1404. case "mask":
  1405. //resolve possible aliases given by options
  1406. resolveAlias(opts.alias, options, opts);
  1407. maskset = generateMaskSet(opts);
  1408. if (maskset.length == 0) { return this; }
  1409. return this.each(function () {
  1410. if ($.isArray(maskset)) {
  1411. multiMaskScope(this, maskset, opts);
  1412. } else
  1413. maskScope($.extend(true, {}, maskset), opts, { "action": "mask", "el": this });
  1414. });
  1415. case "unmaskedvalue":
  1416. var $input = $(this), input = this;
  1417. if ($input.data('_inputmask')) {
  1418. maskset = $input.data('_inputmask')['maskset'];
  1419. opts = $input.data('_inputmask')['opts'];
  1420. return maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input });
  1421. } else return $input.val();
  1422. case "remove":
  1423. return this.each(function () {
  1424. var $input = $(this), input = this;
  1425. if ($input.data('_inputmask')) {
  1426. maskset = $input.data('_inputmask')['maskset'];
  1427. opts = $input.data('_inputmask')['opts'];
  1428. //writeout the unmaskedvalue
  1429. input._valueSet(maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true }));
  1430. //clear data
  1431. $input.removeData('_inputmask');
  1432. //unbind all events
  1433. $input.unbind(".inputmask");
  1434. $input.removeClass('focus.inputmask');
  1435. //restore the value property
  1436. var valueProperty;
  1437. if (Object.getOwnPropertyDescriptor)
  1438. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  1439. if (valueProperty && valueProperty.get) {
  1440. if (input._valueGet) {
  1441. Object.defineProperty(input, "value", {
  1442. get: input._valueGet,
  1443. set: input._valueSet
  1444. });
  1445. }
  1446. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  1447. if (input._valueGet) {
  1448. input.__defineGetter__("value", input._valueGet);
  1449. input.__defineSetter__("value", input._valueSet);
  1450. }
  1451. }
  1452. try { //try catch needed for IE7 as it does not supports deleting fns
  1453. delete input._valueGet;
  1454. delete input._valueSet;
  1455. } catch (e) {
  1456. input._valueGet = undefined;
  1457. input._valueSet = undefined;
  1458. }
  1459. }
  1460. });
  1461. break;
  1462. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1463. if (this.data('_inputmask')) {
  1464. maskset = this.data('_inputmask')['maskset'];
  1465. return maskset['_buffer'].join('');
  1466. }
  1467. else return "";
  1468. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1469. return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
  1470. case "isComplete":
  1471. if (this.data('_inputmask')) {
  1472. maskset = this.data('_inputmask')['maskset'];
  1473. opts = this.data('_inputmask')['opts'];
  1474. return maskScope(maskset, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split('') });
  1475. } else return true;
  1476. case "getmetadata": //return mask metadata if exists
  1477. if (this.data('_inputmask')) {
  1478. maskset = this.data('_inputmask')['maskset'];
  1479. return maskset['metadata'];
  1480. }
  1481. else return undefined;
  1482. default:
  1483. //check if the fn is an alias
  1484. if (!resolveAlias(fn, options, opts)) {
  1485. //maybe fn is a mask so we try
  1486. //set mask
  1487. opts.mask = fn;
  1488. }
  1489. maskset = generateMaskSet(opts);
  1490. if (maskset == undefined) { return this; }
  1491. return this.each(function () {
  1492. if ($.isArray(maskset)) {
  1493. multiMaskScope(this, maskset, opts);
  1494. } else
  1495. maskScope($.extend(true, {}, maskset), opts, { "action": "mask", "el": this });
  1496. });
  1497. break;
  1498. }
  1499. } else if (typeof fn == "object") {
  1500. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1501. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1502. maskset = generateMaskSet(opts);
  1503. if (maskset == undefined) { return this; }
  1504. return this.each(function () {
  1505. if ($.isArray(maskset)) {
  1506. multiMaskScope(this, maskset, opts);
  1507. } else
  1508. maskScope($.extend(true, {}, maskset), opts, { "action": "mask", "el": this });
  1509. });
  1510. } else if (fn == undefined) {
  1511. //look for data-inputmask atribute - the attribute should only contain optipns
  1512. return this.each(function () {
  1513. var attrOptions = $(this).attr("data-inputmask");
  1514. if (attrOptions && attrOptions != "") {
  1515. try {
  1516. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1517. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1518. $.extend(true, dataoptions, options);
  1519. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1520. resolveAlias(opts.alias, dataoptions, opts);
  1521. opts.alias = undefined;
  1522. $(this).inputmask(opts);
  1523. } catch (ex) { } //need a more relax parseJSON
  1524. }
  1525. });
  1526. }
  1527. };
  1528. }
  1529. })(jQuery);