jquery.inputmask.js 96 KB

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