jquery.inputmask.js 81 KB

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