jquery.inputmask.js 96 KB

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