jquery.inputmask.js 81 KB

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