jquery.inputmask.js 80 KB

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