jquery.inputmask.js 88 KB

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