jquery.inputmask.js 80 KB

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