jquery.inputmask.js 80 KB

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