jquery.inputmask.js 88 KB

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