jquery.inputmask.js 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  1. /*
  2. * 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. evName = 'on' + eventName,
  14. isSupported = (evName in el);
  15. if (!isSupported) {
  16. el.setAttribute(evName, 'return;');
  17. isSupported = typeof el[evName] == 'function';
  18. }
  19. el = null;
  20. return isSupported;
  21. }
  22. function isInputTypeSupported(inputType) {
  23. var isSupported = inputType == "text" || inputType == "tel";
  24. if (!isSupported) {
  25. var el = document.createElement('input');
  26. el.setAttribute("type", inputType);
  27. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  28. el = null;
  29. }
  30. return isSupported;
  31. }
  32. function resolveAlias(aliasStr, options, opts) {
  33. var aliasDefinition = opts.aliases[aliasStr];
  34. if (aliasDefinition) {
  35. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  36. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  37. $.extend(true, opts, options); //reapply extra given options
  38. return true;
  39. }
  40. return false;
  41. }
  42. function generateMaskSet(opts, multi) {
  43. var ms = undefined;
  44. function analyseMask(mask) {
  45. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  46. escaped = false;
  47. function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  48. this.matches = [];
  49. this.isGroup = isGroup || false;
  50. this.isOptional = isOptional || false;
  51. this.isQuantifier = isQuantifier || false;
  52. this.isAlternator = isAlternator || false;
  53. this.quantifier = { min: 1, max: 1 };
  54. };
  55. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  56. function insertTestDefinition(mtoken, element, position) {
  57. var maskdef = opts.definitions[element];
  58. var newBlockMarker = mtoken.matches.length == 0;
  59. position = position != undefined ? position : mtoken.matches.length;
  60. if (maskdef && !escaped) {
  61. maskdef["placeholder"] = $.isFunction(maskdef["placeholder"]) ? maskdef["placeholder"].call(this, opts) : maskdef["placeholder"];
  62. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  63. for (var i = 1; i < maskdef.cardinality; i++) {
  64. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  65. 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, placeholder: maskdef["placeholder"], mask: element });
  66. }
  67. 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, placeholder: maskdef["placeholder"], mask: element });
  68. } else {
  69. mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element, placeholder: undefined, mask: element });
  70. escaped = false;
  71. }
  72. }
  73. var currentToken = new maskToken(),
  74. match,
  75. m,
  76. openenings = [],
  77. maskTokens = [],
  78. openingToken,
  79. currentOpeningToken,
  80. alternator,
  81. lastMatch;
  82. while (match = tokenizer.exec(mask)) {
  83. m = match[0];
  84. switch (m.charAt(0)) {
  85. case opts.optionalmarker.end:
  86. // optional closing
  87. case opts.groupmarker.end:
  88. // Group closing
  89. openingToken = openenings.pop();
  90. if (openenings.length > 0) {
  91. currentOpeningToken = openenings[openenings.length - 1];
  92. currentOpeningToken["matches"].push(openingToken);
  93. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  94. alternator = openenings.pop();
  95. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  96. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  97. }
  98. if (openenings.length > 0) {
  99. currentOpeningToken = openenings[openenings.length - 1];
  100. currentOpeningToken["matches"].push(alternator);
  101. } else {
  102. currentToken.matches.push(alternator);
  103. }
  104. }
  105. } else {
  106. currentToken.matches.push(openingToken);
  107. }
  108. break;
  109. case opts.optionalmarker.start:
  110. // optional opening
  111. openenings.push(new maskToken(false, true));
  112. break;
  113. case opts.groupmarker.start:
  114. // Group opening
  115. openenings.push(new maskToken(true));
  116. break;
  117. case opts.quantifiermarker.start:
  118. //Quantifier
  119. var quantifier = new maskToken(false, false, true);
  120. m = m.replace(/[{}]/g, "");
  121. var mq = m.split(","),
  122. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  123. mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  124. if (mq1 == "*" || mq1 == "+") {
  125. mq0 = mq1 == "*" ? 0 : 1;
  126. }
  127. quantifier.quantifier = { min: mq0, max: mq1 };
  128. if (openenings.length > 0) {
  129. var matches = openenings[openenings.length - 1]["matches"];
  130. match = matches.pop();
  131. if (!match["isGroup"]) {
  132. var groupToken = new maskToken(true);
  133. groupToken.matches.push(match);
  134. match = groupToken;
  135. }
  136. matches.push(match);
  137. matches.push(quantifier);
  138. } else {
  139. match = currentToken.matches.pop();
  140. if (!match["isGroup"]) {
  141. var groupToken = new maskToken(true);
  142. groupToken.matches.push(match);
  143. match = groupToken;
  144. }
  145. currentToken.matches.push(match);
  146. currentToken.matches.push(quantifier);
  147. }
  148. break;
  149. case opts.escapeChar:
  150. escaped = true;
  151. break;
  152. case opts.alternatormarker:
  153. if (openenings.length > 0) {
  154. currentOpeningToken = openenings[openenings.length - 1];
  155. lastMatch = currentOpeningToken.matches.pop();
  156. } else {
  157. lastMatch = currentToken.matches.pop();
  158. }
  159. if (lastMatch.isAlternator) {
  160. openenings.push(lastMatch);
  161. } else {
  162. alternator = new maskToken(false, false, false, true);
  163. alternator.matches.push(lastMatch);
  164. openenings.push(alternator);
  165. }
  166. break;
  167. default:
  168. if (openenings.length > 0) {
  169. currentOpeningToken = openenings[openenings.length - 1];
  170. if (currentOpeningToken.matches.length > 0) {
  171. lastMatch = currentOpeningToken.matches[currentOpeningToken.matches.length - 1];
  172. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  173. lastMatch.isGroup = false;
  174. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  175. insertTestDefinition(lastMatch, opts.groupmarker.end);
  176. }
  177. }
  178. insertTestDefinition(currentOpeningToken, m);
  179. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  180. alternator = openenings.pop();
  181. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  182. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  183. }
  184. if (openenings.length > 0) {
  185. currentOpeningToken = openenings[openenings.length - 1];
  186. currentOpeningToken["matches"].push(alternator);
  187. } else {
  188. currentToken.matches.push(alternator);
  189. }
  190. }
  191. } else {
  192. if (currentToken.matches.length > 0) {
  193. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  194. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  195. lastMatch.isGroup = false;
  196. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  197. insertTestDefinition(lastMatch, opts.groupmarker.end);
  198. }
  199. }
  200. insertTestDefinition(currentToken, m);
  201. }
  202. }
  203. }
  204. if (currentToken.matches.length > 0) {
  205. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  206. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  207. lastMatch.isGroup = false;
  208. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  209. insertTestDefinition(lastMatch, opts.groupmarker.end);
  210. }
  211. maskTokens.push(currentToken);
  212. }
  213. //console.log(JSON.stringify(maskTokens));
  214. return maskTokens;
  215. }
  216. function generateMask(mask, metadata) {
  217. if (mask == undefined || mask == "")
  218. return undefined;
  219. else {
  220. if (mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  221. opts.placeholder = "";
  222. } //hide placeholder with single non-greedy mask
  223. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  224. var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
  225. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  226. }
  227. if ($.inputmask.masksCache[mask] == undefined) {
  228. $.inputmask.masksCache[mask] = {
  229. "mask": mask,
  230. "maskToken": analyseMask(mask),
  231. "validPositions": {},
  232. "_buffer": undefined,
  233. "buffer": undefined,
  234. "tests": {},
  235. "metadata": metadata
  236. };
  237. }
  238. return $.extend(true, {}, $.inputmask.masksCache[mask]);
  239. }
  240. }
  241. function preProcessMask(mask) {
  242. mask = mask.toString();
  243. if (opts.numericInput) { //TODO FIX FOR DYNAMIC MASKS WITH QUANTIFIERS
  244. mask = mask.split('').reverse();
  245. for (var ndx = 0; ndx < mask.length; ndx++) {
  246. if (mask[ndx] == opts.optionalmarker.start)
  247. mask[ndx] = opts.optionalmarker.end;
  248. else if (mask[ndx] == opts.optionalmarker.end)
  249. mask[ndx] = opts.optionalmarker.start;
  250. else if (mask[ndx] == opts.groupmarker.start)
  251. mask[ndx] = opts.groupmarker.end;
  252. else if (mask[ndx] == opts.groupmarker.end)
  253. mask[ndx] = opts.groupmarker.start;
  254. }
  255. mask = mask.join('');
  256. }
  257. return mask;
  258. }
  259. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  260. opts.mask = opts.mask.call(this, opts);
  261. }
  262. if ($.isArray(opts.mask)) {
  263. if (multi) { //remove me
  264. ms = [];
  265. $.each(opts.mask, function (ndx, msk) {
  266. if (msk["mask"] != undefined && !$.isFunction(msk["mask"])) {
  267. ms.push(generateMask(preProcessMask(msk["mask"]), msk));
  268. } else {
  269. ms.push(generateMask(preProcessMask(msk), msk));
  270. }
  271. });
  272. } else {
  273. opts.keepStatic = opts.keepStatic == undefined ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  274. var altMask = "(";
  275. $.each(opts.mask, function (ndx, msk) {
  276. if (altMask.length > 1)
  277. altMask += ")|(";
  278. if (msk["mask"] != undefined && !$.isFunction(msk["mask"])) {
  279. altMask += preProcessMask(msk["mask"]);
  280. } else {
  281. altMask += preProcessMask(msk);
  282. }
  283. });
  284. altMask += ")";
  285. ms = generateMask(altMask, opts.mask);
  286. }
  287. } else {
  288. if (opts.mask) {
  289. if (opts.mask["mask"] != undefined && !$.isFunction(opts.mask["mask"])) {
  290. ms = generateMask(preProcessMask(opts.mask["mask"]), opts.mask);
  291. } else {
  292. ms = generateMask(preProcessMask(opts.mask), opts.mask);
  293. }
  294. }
  295. }
  296. return ms;
  297. }
  298. var ua = navigator.userAgent,
  299. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  300. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  301. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  302. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  303. 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),
  304. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  305. //if (androidchrome) {
  306. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  307. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  308. // androidchrome32 = (version == 32);
  309. //}
  310. //masking scope
  311. //actionObj definition see below
  312. function maskScope(actionObj, maskset, opts) {
  313. var isRTL = false,
  314. undoValue,
  315. compositionUpdateData,
  316. $el,
  317. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  318. skipInputEvent = false, //skip when triggered from within inputmask
  319. ignorable = false,
  320. maxLength,
  321. firstClick = true;
  322. //maskset helperfunctions
  323. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  324. minimalPos = minimalPos || 0;
  325. var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos;
  326. do {
  327. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  328. var validPos = getMaskSet()['validPositions'][pos];
  329. test = validPos["match"];
  330. ndxIntlzr = validPos["locator"].slice();
  331. maskTemplate.push(includeInput === true ? validPos["input"] : getPlaceholder(pos, test));
  332. } else {
  333. if (minimalPos > pos) {
  334. var testPositions = getTests(pos, ndxIntlzr, pos - 1);
  335. testPos = testPositions[0];
  336. } else {
  337. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  338. }
  339. test = testPos["match"];
  340. ndxIntlzr = testPos["locator"].slice();
  341. maskTemplate.push(getPlaceholder(pos, test));
  342. }
  343. pos++;
  344. } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  345. maskTemplate.pop(); //drop the last one which is empty
  346. return maskTemplate;
  347. }
  348. function getMaskSet() {
  349. return maskset;
  350. }
  351. function resetMaskSet(soft) {
  352. var maskset = getMaskSet();
  353. maskset["buffer"] = undefined;
  354. maskset["tests"] = {};
  355. if (soft !== true) {
  356. maskset["_buffer"] = undefined;
  357. maskset["validPositions"] = {};
  358. maskset["p"] = 0;
  359. }
  360. }
  361. function getLastValidPosition(closestTo) {
  362. var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset["validPositions"];
  363. if (closestTo == undefined) closestTo = -1;
  364. var before = lastValidPosition, after = lastValidPosition;
  365. for (var posNdx in valids) {
  366. var psNdx = parseInt(posNdx);
  367. if (closestTo == -1 || valids[psNdx]["match"].fn != null) {
  368. if (psNdx <= closestTo) before = psNdx;
  369. if (psNdx >= closestTo) after = psNdx;
  370. }
  371. }
  372. lastValidPosition = (closestTo - before) > 1 || after < closestTo ? before : after;
  373. return lastValidPosition;
  374. }
  375. function setValidPosition(pos, validTest, fromSetValid) {
  376. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  377. //reposition & revalidate others
  378. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]), lvp = getLastValidPosition(), i;
  379. for (i = pos; i <= lvp; i++) { //clear selection
  380. delete getMaskSet()["validPositions"][i];
  381. }
  382. getMaskSet()["validPositions"][pos] = validTest;
  383. var valid = true, j;
  384. for (i = pos; i <= lvp ; i++) {
  385. var t = positionsClone[i];
  386. if (t != undefined) {
  387. var vps = getMaskSet()["validPositions"];
  388. if (!opts.keepStatic && vps[i] && (vps[i + 1] != undefined && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || vps[i].alternation != undefined))
  389. j = i + 1;
  390. else
  391. j = seekNext(i);
  392. if (positionCanMatchDefinition(j, t["match"].def)) {
  393. valid = valid && (isValid(j, t["input"], true, true) !== false);
  394. } else valid = t["match"].fn == null;
  395. }
  396. if (!valid) break;
  397. }
  398. if (!valid) {
  399. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  400. return false;
  401. }
  402. } else
  403. getMaskSet()["validPositions"][pos] = validTest;
  404. return true;
  405. }
  406. function stripValidPositions(start, end) {
  407. var i, startPos = start;
  408. if (getMaskSet()["validPositions"][start] != undefined && getMaskSet()["validPositions"][start].input == opts.radixPoint) {
  409. end++;
  410. startPos++;
  411. }
  412. for (i = startPos; i < end; i++) { //clear selection
  413. if (getMaskSet()["validPositions"][i] != undefined &&
  414. (getMaskSet()["validPositions"][i].input != opts.radixPoint || i == getLastValidPosition()))
  415. delete getMaskSet()["validPositions"][i];
  416. }
  417. for (i = end ; i <= getLastValidPosition() ;) {
  418. var t = getMaskSet()["validPositions"][i];
  419. var s = getMaskSet()["validPositions"][startPos];
  420. if (t != undefined && s == undefined) {
  421. if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) {
  422. delete getMaskSet()["validPositions"][i];
  423. i++;
  424. }
  425. startPos++;
  426. } else i++;
  427. }
  428. //remove radixpoint if needed
  429. var lvp = getLastValidPosition();
  430. if (start <= lvp && getMaskSet()["validPositions"][lvp] != undefined && (getMaskSet()["validPositions"][lvp].input == opts.radixPoint))
  431. delete getMaskSet()["validPositions"][lvp];
  432. resetMaskSet(true);
  433. }
  434. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  435. var testPositions = getTests(pos, ndxIntlzr, tstPs),
  436. testPos,
  437. lvp = getLastValidPosition(),
  438. lvTest = getMaskSet()["validPositions"][lvp] || getTests(0)[0],
  439. lvTestAltArr = (lvTest.alternation != undefined) ? lvTest["locator"][lvTest.alternation].split(",") : [];
  440. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  441. testPos = testPositions[ndx];
  442. if (opts.greedy ||
  443. ((testPos["match"] && (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true) &&
  444. (lvTest.alternation == undefined ||
  445. (testPos["locator"][lvTest.alternation] != undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  446. break;
  447. }
  448. }
  449. return testPos;
  450. }
  451. function getTest(pos) {
  452. if (getMaskSet()['validPositions'][pos]) {
  453. return getMaskSet()['validPositions'][pos]["match"];
  454. }
  455. return getTests(pos)[0]["match"];
  456. }
  457. function positionCanMatchDefinition(pos, def) {
  458. var valid = false, tests = getTests(pos);
  459. for (var tndx = 0; tndx < tests.length; tndx++) {
  460. if (tests[tndx]["match"] && tests[tndx]["match"].def == def) {
  461. valid = true;
  462. break;
  463. }
  464. }
  465. return valid;
  466. };
  467. function getTests(pos, ndxIntlzr, tstPs) {
  468. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  469. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  470. function handleMatch(match, loopNdx, quantifierRecurse) {
  471. if (testPos > 10000) {
  472. alert("jquery.inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet()["mask"]);
  473. return true;
  474. }
  475. if (testPos == pos && match.matches == undefined) {
  476. matches.push({ "match": match, "locator": loopNdx.reverse() });
  477. return true;
  478. } else if (match.matches != undefined) {
  479. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  480. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  481. if (match) return true;
  482. } else if (match.isOptional) {
  483. var optionalToken = match;
  484. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  485. if (match) {
  486. var latestMatch = matches[matches.length - 1]["match"];
  487. var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
  488. if (isFirstMatch) {
  489. insertStop = true; //insert a stop for non greedy
  490. }
  491. testPos = pos; //match the position after the group
  492. }
  493. } else if (match.isAlternator) {
  494. var alternateToken = match, malternateMatches = [], maltMatches,
  495. currentMatches = matches.slice(), loopNdxCnt = loopNdx.length;
  496. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  497. if (altIndex == -1 || typeof altIndex == "string") {
  498. var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr;
  499. if (typeof altIndex == "string") altIndexArr = altIndex.split(",");
  500. for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  501. matches = [];
  502. match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  503. maltMatches = matches.slice();
  504. testPos = currentPos;
  505. matches = [];
  506. //cloneback
  507. for (var i = 0; i < ndxInitializerClone.length; i++) {
  508. ndxInitializer[i] = ndxInitializerClone[i];
  509. }
  510. //fuzzy merge matches
  511. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  512. var altMatch = maltMatches[ndx1];
  513. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  514. var altMatch2 = malternateMatches[ndx2];
  515. //verify equality
  516. if (altMatch.match.mask == altMatch2.match.mask && (typeof altIndex != "string" || $.inArray(altMatch.locator[loopNdxCnt].toString(), altIndexArr) != -1)) {
  517. maltMatches.splice(ndx1, 1);
  518. altMatch2.locator[loopNdxCnt] = altMatch2.locator[loopNdxCnt] + "," + altMatch.locator[loopNdxCnt];
  519. altMatch2.alternation = loopNdxCnt; //we pass the alternation index => used in determineLastRequiredPosition
  520. break;
  521. }
  522. }
  523. }
  524. malternateMatches = malternateMatches.concat(maltMatches);
  525. }
  526. if (typeof altIndex == "string") { //filter matches
  527. malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {
  528. if (isFinite(ndx)) {
  529. var altLocArr = lmnt.locator[loopNdxCnt].toString().split(",");
  530. var mamatch;
  531. lmnt.locator[loopNdxCnt] = undefined;
  532. lmnt.alternation = undefined;
  533. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  534. mamatch = $.inArray(altLocArr[alndx], altIndexArr) != -1;
  535. if (mamatch) { //rebuild the locator with valid entries
  536. if (lmnt.locator[loopNdxCnt] != undefined) {
  537. lmnt.locator[loopNdxCnt] += ",";
  538. lmnt.alternation = loopNdxCnt; //only define alternation when there is more then 1 possibility
  539. lmnt.locator[loopNdxCnt] += altLocArr[alndx];
  540. } else
  541. lmnt.locator[loopNdxCnt] = parseInt(altLocArr[alndx]);
  542. }
  543. }
  544. if (lmnt.locator[loopNdxCnt] != undefined) return lmnt;
  545. }
  546. });
  547. }
  548. matches = currentMatches.concat(malternateMatches);
  549. //console.log("alternates " + pos + " -> " + JSON.stringify(matches));
  550. insertStop = true; //insert a stopelemnt when there is an alternate
  551. } else {
  552. match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  553. }
  554. if (match) return true;
  555. } else if (match.isQuantifier && quantifierRecurse !== true) {
  556. var qt = match;
  557. opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!)
  558. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  559. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  560. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  561. if (match) {
  562. //get latest match
  563. var latestMatch = matches[matches.length - 1]["match"];
  564. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  565. var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
  566. if (isFirstMatch) { //search for next possible match
  567. if (qndx > (qt.quantifier.min - 1)) {
  568. insertStop = true;
  569. testPos = pos; //match the position after the group
  570. break; //stop quantifierloop
  571. } else return true;
  572. } else {
  573. return true;
  574. }
  575. }
  576. }
  577. } else {
  578. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  579. if (match)
  580. return true;
  581. }
  582. } else testPos++;
  583. }
  584. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  585. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  586. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  587. if (match && testPos == pos) {
  588. return match;
  589. } else if (testPos > pos) {
  590. break;
  591. }
  592. }
  593. }
  594. }
  595. //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  596. // return getMaskSet()['tests'][pos];
  597. //}
  598. if (ndxIntlzr == undefined) {
  599. var previousPos = pos - 1, test;
  600. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  601. previousPos--;
  602. }
  603. if (test != undefined && previousPos > -1) {
  604. testPos = previousPos;
  605. ndxInitializer = test["locator"].slice();
  606. } else {
  607. previousPos = pos - 1;
  608. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  609. previousPos--;
  610. }
  611. if (test != undefined && previousPos > -1) {
  612. testPos = previousPos;
  613. ndxInitializer = test[0]["locator"].slice();
  614. }
  615. }
  616. }
  617. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  618. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  619. if ((match && testPos == pos) || testPos > pos) {
  620. break;
  621. }
  622. }
  623. if (matches.length == 0 || insertStop)
  624. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  625. getMaskSet()['tests'][pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  626. //console.log(pos + " - " + JSON.stringify(matches));
  627. return getMaskSet()['tests'][pos];
  628. }
  629. function getBufferTemplate() {
  630. if (getMaskSet()['_buffer'] == undefined) {
  631. //generate template
  632. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  633. }
  634. return getMaskSet()['_buffer'];
  635. }
  636. function getBuffer() {
  637. if (getMaskSet()['buffer'] == undefined) {
  638. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  639. }
  640. return getMaskSet()['buffer'];
  641. }
  642. function refreshFromBuffer(start, end, buffer) {
  643. buffer = buffer || getBuffer().slice(); //pass or work on clone
  644. if (start === true) {
  645. resetMaskSet();
  646. start = 0;
  647. end = buffer.length;
  648. } else {
  649. for (var i = start; i < end; i++) {
  650. delete getMaskSet()["validPositions"][i];
  651. delete getMaskSet()["tests"][i];
  652. }
  653. }
  654. for (var i = start; i < end; i++) {
  655. if (buffer[i] != opts.skipOptionalPartCharacter) {
  656. isValid(i, buffer[i], true, true);
  657. }
  658. }
  659. }
  660. function casing(elem, test) {
  661. switch (test.casing) {
  662. case "upper":
  663. elem = elem.toUpperCase();
  664. break;
  665. case "lower":
  666. elem = elem.toLowerCase();
  667. break;
  668. }
  669. return elem;
  670. }
  671. function checkAlternationMatch(altArr1, altArr2) {
  672. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  673. isMatch = false;
  674. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  675. if ($.inArray(altArr1[alndx], altArrC) != -1) {
  676. isMatch = true;
  677. break;
  678. }
  679. }
  680. return isMatch;
  681. }
  682. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  683. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  684. function _isValid(position, c, strict, fromSetValid) {
  685. var rslt = false;
  686. $.each(getTests(position), function (ndx, tst) {
  687. var test = tst["match"];
  688. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  689. for (var i = test.cardinality; i > loopend; i--) {
  690. chrs += getBufferElement(position - (i - 1));
  691. }
  692. if (c) {
  693. chrs += c;
  694. }
  695. //return is false or a json object => { pos: ??, c: ??} or true
  696. rslt = test.fn != null ?
  697. test.fn.test(chrs, getMaskSet(), position, strict, opts)
  698. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  699. { c: test["def"], pos: position }
  700. : false;
  701. if (rslt !== false) {
  702. var elem = rslt.c != undefined ? rslt.c : c;
  703. elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
  704. var validatedPos = position;
  705. if (rslt["remove"] != undefined) { //remove position
  706. stripValidPositions(rslt["remove"], rslt["remove"] + 1);
  707. }
  708. if (rslt["refreshFromBuffer"]) {
  709. var refresh = rslt["refreshFromBuffer"];
  710. strict = true;
  711. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
  712. if (rslt.pos == undefined && rslt.c == undefined) {
  713. rslt.pos = getLastValidPosition();
  714. return false;//breakout if refreshFromBuffer && nothing to insert
  715. }
  716. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  717. if (validatedPos != position) {
  718. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  719. return false;
  720. }
  721. } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
  722. validatedPos = rslt["pos"];
  723. refreshFromBuffer(position, validatedPos);
  724. if (validatedPos != position) {
  725. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  726. return false;
  727. }
  728. }
  729. if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
  730. return false; //breakout if nothing to insert
  731. }
  732. if (ndx > 0) {
  733. resetMaskSet(true);
  734. }
  735. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid))
  736. rslt = false;
  737. return false; //break from $.each
  738. }
  739. });
  740. return rslt;
  741. }
  742. function alternate(pos, c, strict, fromSetValid) {
  743. var validPsClone = $.extend(true, {}, getMaskSet()["validPositions"]),
  744. lastAlt,
  745. alternation;
  746. //find last alternation
  747. for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) {
  748. if (getMaskSet()["validPositions"][lastAlt] && getMaskSet()["validPositions"][lastAlt].alternation != undefined) {
  749. alternation = getMaskSet()["validPositions"][lastAlt].alternation;
  750. break;
  751. }
  752. }
  753. if (alternation != undefined) {
  754. //find first decision making position
  755. for (var decisionPos in getMaskSet()["validPositions"]) {
  756. if (parseInt(decisionPos) > parseInt(lastAlt) && getMaskSet()["validPositions"][decisionPos].alternation === undefined) {
  757. var altPos = getMaskSet()["validPositions"][decisionPos],
  758. decisionTaker = altPos.locator[alternation],
  759. altNdxs = getMaskSet()["validPositions"][lastAlt].locator[alternation].split(",");
  760. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  761. if (decisionTaker < altNdxs[mndx]) {
  762. var possibilityPos, possibilities;
  763. for (var dp = decisionPos - 1; dp >= 0; dp--) {
  764. possibilityPos = getMaskSet()["validPositions"][dp];
  765. if (possibilityPos != undefined) {
  766. possibilities = possibilityPos.locator[alternation]; //store to reset
  767. possibilityPos.locator[alternation] = altNdxs[mndx];
  768. break;
  769. }
  770. }
  771. if (decisionTaker != possibilityPos.locator[alternation]) {
  772. var buffer = getBuffer().slice(); //work on clone
  773. for (var i = decisionPos; i < getLastValidPosition() + 1; i++) {
  774. delete getMaskSet()["validPositions"][i];
  775. delete getMaskSet()["tests"][i];
  776. }
  777. resetMaskSet(true); //clear getbuffer
  778. opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
  779. for (var i = decisionPos; i < buffer.length; i++) {
  780. if (buffer[i] != opts.skipOptionalPartCharacter) {
  781. isValid(getLastValidPosition() + 1, buffer[i], false, true);
  782. }
  783. }
  784. possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete
  785. var isValidRslt = isValid(pos, c, strict, fromSetValid);
  786. opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength
  787. if (!isValidRslt) {
  788. resetMaskSet();
  789. getMaskSet()["validPositions"] = $.extend(true, {}, validPsClone);
  790. } else
  791. return isValidRslt;
  792. }
  793. }
  794. }
  795. break;
  796. }
  797. }
  798. }
  799. return false;
  800. }
  801. //set alternator choice on previous skipped placeholder positions
  802. function trackbackAlternations(originalPos, newPos) {
  803. var vp = getMaskSet()["validPositions"][newPos],
  804. targetLocator = vp.locator,
  805. tll = targetLocator.length;
  806. for (var ps = originalPos; ps < newPos; ps++) {
  807. if (!isMask(ps)) {
  808. var tests = getTests(ps),
  809. bestMatch = tests[0], equality = -1;
  810. $.each(tests, function (ndx, tst) {
  811. for (var i = 0; i < tll; i++) {
  812. if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(','), targetLocator[i].toString().split(',')) && equality < i) {
  813. equality = i;
  814. bestMatch = tst;
  815. }
  816. }
  817. });
  818. setValidPosition(ps, $.extend({}, bestMatch, { "input": bestMatch["match"].def }), true)
  819. }
  820. }
  821. }
  822. //Check for a nonmask before the pos
  823. var buffer = getBuffer();
  824. for (var pndx = pos - 1; pndx > -1; pndx--) {
  825. if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx]["match"].fn == null)
  826. break;
  827. else if (getMaskSet()["validPositions"][pndx] == undefined && (!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) {
  828. _isValid(pndx, buffer[pndx], true);
  829. }
  830. }
  831. var maskPos = pos;
  832. var result = false;
  833. if (fromSetValid && maskPos >= getMaskLength()) {
  834. resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length
  835. }
  836. if (maskPos < getMaskLength()) {
  837. result = _isValid(maskPos, c, strict, fromSetValid);
  838. if (!strict && result === false) {
  839. var currentPosValid = getMaskSet()["validPositions"][maskPos];
  840. if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
  841. result = { "caret": seekNext(maskPos) };
  842. } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
  843. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  844. result = _isValid(nPos, c, strict, fromSetValid);
  845. if (result !== false) {
  846. trackbackAlternations(maskPos, nPos);
  847. maskPos = nPos;
  848. break;
  849. }
  850. }
  851. }
  852. }
  853. }
  854. if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic
  855. result = alternate(pos, c, strict, fromSetValid);
  856. }
  857. if (result === true) result = { "pos": maskPos };
  858. return result;
  859. }
  860. function isMask(pos) {
  861. var test = getTest(pos);
  862. return test.fn != null ? test.fn : false;
  863. }
  864. function getMaskLength() {
  865. var maskLength;
  866. maxLength = $el.prop('maxLength');
  867. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  868. if (opts.greedy == false) {
  869. var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp],
  870. ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
  871. for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
  872. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  873. ndxIntlzr = testPos["locator"].slice();
  874. }
  875. maskLength = pos;
  876. } else
  877. maskLength = getBuffer().length;
  878. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  879. }
  880. function seekNext(pos) {
  881. var maskL = getMaskLength();
  882. if (pos >= maskL) return maskL;
  883. var position = pos;
  884. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
  885. }
  886. return position;
  887. }
  888. function seekPrevious(pos) {
  889. var position = pos;
  890. if (position <= 0) return 0;
  891. while (--position > 0 && !isMask(position)) {
  892. };
  893. return position;
  894. }
  895. function getBufferElement(position) {
  896. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  897. }
  898. function writeBuffer(input, buffer, caretPos) {
  899. input._valueSet(buffer.join(''));
  900. if (caretPos != undefined) {
  901. caret(input, caretPos);
  902. }
  903. }
  904. function getPlaceholder(pos, test) {
  905. test = test || getTest(pos);
  906. return test["placeholder"] != undefined ? test["placeholder"] : (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  907. }
  908. function checkVal(input, writeOut, strict, nptvl) {
  909. var inputValue = nptvl != undefined ? nptvl.slice() : input._valueGet().split('');
  910. resetMaskSet();
  911. if (writeOut) input._valueSet(""); //initial clear
  912. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(''), matches = inputValue.join('').match(new RegExp(escapeRegex(staticInput), "g"));
  913. if (matches && matches.length > 1) {
  914. inputValue.splice(0, staticInput.length);
  915. }
  916. $.each(inputValue, function (ndx, charCode) {
  917. var keypress = $.Event("keypress");
  918. keypress.which = charCode.charCodeAt(0);
  919. var lvp = getLastValidPosition(), lvTest = getMaskSet()["validPositions"][lvp], nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  920. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, getMaskSet()["p"])) == -1 || strict) {
  921. var pos = strict ? ndx : (nextTest["match"].fn == null && (lvp + 1) < getMaskSet()["p"] ? lvp + 1 : getMaskSet()["p"]);
  922. keypressEvent.call(input, keypress, true, false, strict, pos);
  923. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  924. } else {
  925. keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  926. }
  927. });
  928. if (writeOut) {
  929. var keypressResult = opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
  930. handleOnKeyResult(input, keypressResult);
  931. //writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined);
  932. var forwardPosition = getMaskSet()["p"];
  933. writeBuffer(input, getBuffer(), $(input).is(":focus") ? (opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition) : undefined);
  934. }
  935. }
  936. function escapeRegex(str) {
  937. return $.inputmask.escapeRegex.call(this, str);
  938. }
  939. function unmaskedvalue($input) {
  940. if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
  941. var umValue = [], vps = getMaskSet()["validPositions"];
  942. for (var pndx in vps) {
  943. if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
  944. umValue.push(vps[pndx]["input"]);
  945. }
  946. }
  947. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  948. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join('');
  949. if ($.isFunction(opts.onUnMask)) {
  950. unmaskedValue = (opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue);
  951. }
  952. return unmaskedValue;
  953. } else {
  954. return $input[0]._valueGet();
  955. }
  956. }
  957. function TranslatePosition(pos) {
  958. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  959. var bffrLght = getBuffer().length;
  960. pos = bffrLght - pos;
  961. }
  962. return pos;
  963. }
  964. function caret(input, begin, end) {
  965. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  966. if (typeof begin == 'number') {
  967. begin = TranslatePosition(begin);
  968. end = TranslatePosition(end);
  969. end = (typeof end == 'number') ? end : begin;
  970. //store caret for multi scope
  971. var data = $(npt).data('_inputmask') || {};
  972. data["caret"] = { "begin": begin, "end": end };
  973. $(npt).data('_inputmask', data);
  974. if (!$(npt).is(":visible")) {
  975. return;
  976. }
  977. var scrollCalc = $(npt).css("font-size").replace("px", "") * end;
  978. npt.scrollLeft = scrollCalc > npt.scrollWidth ? scrollCalc : 0;
  979. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  980. if (npt.setSelectionRange) {
  981. npt.selectionStart = begin;
  982. npt.selectionEnd = end;
  983. } else if (npt.createTextRange) {
  984. range = npt.createTextRange();
  985. range.collapse(true);
  986. range.moveEnd('character', end);
  987. range.moveStart('character', begin);
  988. range.select();
  989. }
  990. } else {
  991. var data = $(npt).data('_inputmask');
  992. if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
  993. begin = data["caret"]["begin"];
  994. end = data["caret"]["end"];
  995. } else if (npt.setSelectionRange) {
  996. begin = npt.selectionStart;
  997. end = npt.selectionEnd;
  998. } else if (document.selection && document.selection.createRange) {
  999. range = document.selection.createRange();
  1000. begin = 0 - range.duplicate().moveStart('character', -100000);
  1001. end = begin + range.text.length;
  1002. }
  1003. begin = TranslatePosition(begin);
  1004. end = TranslatePosition(end);
  1005. return { "begin": begin, "end": end };
  1006. }
  1007. }
  1008. function determineLastRequiredPosition(returnDefinition) {
  1009. var buffer = getBuffer(), bl = buffer.length,
  1010. pos, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet()["validPositions"][lvp],
  1011. ndxIntlzr = lvTest != undefined ? lvTest["locator"].slice() : undefined, testPos;
  1012. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1013. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1014. ndxIntlzr = testPos["locator"].slice();
  1015. positions[pos] = $.extend(true, {}, testPos);
  1016. }
  1017. var lvTestAltArr = lvTest && lvTest.alternation != undefined ? lvTest["locator"][lvTest.alternation].split(",") : [];
  1018. for (pos = bl - 1; pos > lvp; pos--) {
  1019. testPos = positions[pos]["match"];
  1020. if ((testPos.optionality ||
  1021. testPos.optionalQuantifier ||
  1022. (lvTest && lvTest.alternation != undefined && positions[pos]["locator"][lvTest.alternation] != undefined && $.inArray(positions[pos]["locator"][lvTest.alternation].toString(), lvTestAltArr) != -1))
  1023. && buffer[pos] == getPlaceholder(pos, testPos)) {
  1024. bl--;
  1025. } else break;
  1026. }
  1027. return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
  1028. }
  1029. function clearOptionalTail(buffer) {
  1030. var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
  1031. for (; lmib > rl; lmib--) {
  1032. if (isMask(lmib)) break; //fixme ismask is not good enough
  1033. }
  1034. buffer.splice(rl, lmib + 1 - rl);
  1035. }
  1036. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1037. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  1038. if (opts.repeat == "*") return undefined;
  1039. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
  1040. if (lvp == aml) {
  1041. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
  1042. complete = true;
  1043. for (var i = 0; i <= aml; i++) {
  1044. var mask = isMask(i);
  1045. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  1046. complete = false;
  1047. break;
  1048. }
  1049. }
  1050. }
  1051. }
  1052. return complete;
  1053. }
  1054. function isSelection(begin, end) {
  1055. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  1056. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  1057. }
  1058. function installEventRuler(npt) {
  1059. var events = $._data(npt).events;
  1060. $.each(events, function (eventType, eventHandlers) {
  1061. $.each(eventHandlers, function (ndx, eventHandler) {
  1062. if (eventHandler.namespace == "inputmask") {
  1063. if (eventHandler.type != "setvalue") {
  1064. var handler = eventHandler.handler;
  1065. eventHandler.handler = function (e) {
  1066. //console.log(e.type);
  1067. if (this.readOnly || this.disabled)
  1068. e.preventDefault;
  1069. else {
  1070. switch (e.type) {
  1071. case "input":
  1072. if (skipInputEvent === true) {
  1073. skipInputEvent = false;
  1074. return e.preventDefault;
  1075. }
  1076. break;
  1077. case "keydown":
  1078. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1079. skipKeyPressEvent = false;
  1080. break;
  1081. case "keypress":
  1082. if (skipKeyPressEvent === true)
  1083. return e.preventDefault;
  1084. skipKeyPressEvent = true;
  1085. break;
  1086. case "compositionupdate":
  1087. skipInputEvent = true; //stop inutFallback
  1088. break;
  1089. }
  1090. return handler.apply(this, arguments);
  1091. }
  1092. };
  1093. }
  1094. }
  1095. });
  1096. });
  1097. }
  1098. function patchValueProperty(npt) {
  1099. var valueGet;
  1100. var valueSet;
  1101. function PatchValhook(type) {
  1102. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  1103. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  1104. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1105. elem.value = value;
  1106. return elem;
  1107. };
  1108. $.valHooks[type] = {
  1109. get: function (elem) {
  1110. var $elem = $(elem);
  1111. if ($elem.data('_inputmask')) {
  1112. if ($elem.data('_inputmask')['opts'].autoUnmask)
  1113. return $elem.inputmask('unmaskedvalue');
  1114. else {
  1115. var result = valhookGet(elem),
  1116. inputData = $elem.data('_inputmask'),
  1117. maskset = inputData['maskset'],
  1118. bufferTemplate = maskset['_buffer'];
  1119. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  1120. return result != bufferTemplate ? result : '';
  1121. }
  1122. } else return valhookGet(elem);
  1123. },
  1124. set: function (elem, value) {
  1125. var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
  1126. if (inputData) {
  1127. result = valhookSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value);
  1128. $elem.triggerHandler('setvalue.inputmask');
  1129. } else {
  1130. result = valhookSet(elem, value);
  1131. }
  1132. return result;
  1133. },
  1134. inputmaskpatch: true
  1135. };
  1136. }
  1137. }
  1138. function getter() {
  1139. var $self = $(this), inputData = $(this).data('_inputmask');
  1140. if (inputData) {
  1141. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  1142. } else return valueGet.call(this);
  1143. }
  1144. function setter(value) {
  1145. var inputData = $(this).data('_inputmask');
  1146. if (inputData) {
  1147. valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value);
  1148. $(this).triggerHandler('setvalue.inputmask');
  1149. } else {
  1150. valueSet.call(this, value);
  1151. }
  1152. }
  1153. function InstallNativeValueSetFallback(npt) {
  1154. $(npt).bind("mouseenter.inputmask", function (event) {
  1155. var $input = $(this), input = this, value = input._valueGet();
  1156. if (value != "" && value != getBuffer().join('')) {
  1157. this._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, value, opts) || value) : value);
  1158. $input.trigger("setvalue");
  1159. }
  1160. });
  1161. //!! the bound handlers are executed in the order they where bound
  1162. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1163. var events = $._data(npt).events;
  1164. var handlers = events["mouseover"];
  1165. if (handlers) {
  1166. var ourHandler = handlers[handlers.length - 1];
  1167. for (var i = handlers.length - 1; i > 0; i--) {
  1168. handlers[i] = handlers[i - 1];
  1169. }
  1170. handlers[0] = ourHandler;
  1171. }
  1172. }
  1173. if (!npt._valueGet) {
  1174. //var valueProperty;
  1175. if (Object.getOwnPropertyDescriptor)
  1176. var valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  1177. if (valueProperty && valueProperty.configurable && false) { //experimental for chrome
  1178. npt._value = valueProperty.value;
  1179. valueGet = function () {
  1180. return this._value || "";
  1181. }
  1182. valueSet = function (value) {
  1183. this._value = value;
  1184. this.select();
  1185. this.setRangeText(value);
  1186. this.selectionStart = this.selectionEnd;
  1187. }
  1188. Object.defineProperty(npt, "value", {
  1189. get: getter,
  1190. set: setter
  1191. });
  1192. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1193. valueGet = npt.__lookupGetter__("value");
  1194. valueSet = npt.__lookupSetter__("value");
  1195. npt.__defineGetter__("value", getter);
  1196. npt.__defineSetter__("value", setter);
  1197. } else { //jquery.val
  1198. valueGet = function () { return npt.value; }
  1199. valueSet = function (value) { npt.value = value; }
  1200. PatchValhook(npt.type);
  1201. InstallNativeValueSetFallback(npt);
  1202. }
  1203. npt._valueGet = function () {
  1204. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  1205. };
  1206. npt._valueSet = function (value) {
  1207. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  1208. };
  1209. }
  1210. }
  1211. function handleRemove(input, k, pos) {
  1212. function generalize() {
  1213. if (opts.keepStatic) {
  1214. resetMaskSet(true);
  1215. var validInputs = [],
  1216. lastAlt;
  1217. //find last alternation
  1218. for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) {
  1219. if (getMaskSet()["validPositions"][lastAlt]) {
  1220. if (getMaskSet()["validPositions"][lastAlt].alternation != undefined) {
  1221. break;
  1222. }
  1223. validInputs.push(getMaskSet()["validPositions"][lastAlt].input);
  1224. delete getMaskSet()["validPositions"][lastAlt];
  1225. }
  1226. }
  1227. if (lastAlt > 0) {
  1228. while (validInputs.length > 0) {
  1229. getMaskSet()["p"] = seekNext(getLastValidPosition());
  1230. var keypress = $.Event("keypress");
  1231. keypress.which = validInputs.pop().charCodeAt(0);
  1232. keypressEvent.call(input, keypress, true, false, false, getMaskSet()["p"]);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. if (opts.numericInput || isRTL) {
  1238. if (k == $.inputmask.keyCode.BACKSPACE)
  1239. k = $.inputmask.keyCode.DELETE;
  1240. else if (k == $.inputmask.keyCode.DELETE)
  1241. k = $.inputmask.keyCode.BACKSPACE;
  1242. if (isRTL) {
  1243. var pend = pos.end;
  1244. pos.end = pos.begin;
  1245. pos.begin = pend;
  1246. }
  1247. }
  1248. if (k == $.inputmask.keyCode.BACKSPACE && pos.end - pos.begin <= 1)
  1249. pos.begin = seekPrevious(pos.begin);
  1250. else if (k == $.inputmask.keyCode.DELETE && pos.begin == pos.end)
  1251. pos.end++;
  1252. stripValidPositions(pos.begin, pos.end);
  1253. generalize(); //revert the alternation
  1254. var firstMaskedPos = getLastValidPosition(pos.begin);
  1255. if (firstMaskedPos < pos.begin) {
  1256. if (firstMaskedPos == -1) resetMaskSet();
  1257. getMaskSet()["p"] = seekNext(firstMaskedPos);
  1258. } else {
  1259. getMaskSet()["p"] = pos.begin;
  1260. }
  1261. }
  1262. //postprocessing of the validpositions according to the buffer manipulations
  1263. function handleOnKeyResult(input, keyResult, caretPos) {
  1264. if (keyResult && keyResult["refreshFromBuffer"]) {
  1265. var refresh = keyResult["refreshFromBuffer"];
  1266. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], keyResult["buffer"]);
  1267. resetMaskSet(true);
  1268. if (caretPos != undefined) {
  1269. writeBuffer(input, getBuffer());
  1270. caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
  1271. }
  1272. }
  1273. }
  1274. function keydownEvent(e) {
  1275. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1276. //backspace, delete, and escape get special treatment
  1277. if (k == $.inputmask.keyCode.BACKSPACE || k == $.inputmask.keyCode.DELETE || (iphone && k == 127) || (e.ctrlKey && k == 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1278. e.preventDefault(); //stop default action but allow propagation
  1279. if (k == 88) undoValue = getBuffer().join('');
  1280. handleRemove(input, k, pos);
  1281. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  1282. if (input._valueGet() == getBufferTemplate().join(''))
  1283. $input.trigger('cleared');
  1284. if (opts.showTooltip) { //update tooltip
  1285. $input.prop("title", getMaskSet()["mask"]);
  1286. }
  1287. } else if (k == $.inputmask.keyCode.END || k == $.inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1288. setTimeout(function () {
  1289. var caretPos = seekNext(getLastValidPosition());
  1290. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1291. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1292. }, 0);
  1293. } else if ((k == $.inputmask.keyCode.HOME && !e.shiftKey) || k == $.inputmask.keyCode.PAGE_UP) { //Home or page_up
  1294. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1295. } else if ((opts.undoOnEscape && k == $.inputmask.keyCode.ESCAPE) || (k == 90 && e.ctrlKey)) { //escape && undo
  1296. checkVal(input, true, false, undoValue.split(''));
  1297. $input.click();
  1298. } else if (k == $.inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1299. opts.insertMode = !opts.insertMode;
  1300. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1301. } else if (opts.insertMode == false && !e.shiftKey) {
  1302. if (k == $.inputmask.keyCode.RIGHT) {
  1303. setTimeout(function () {
  1304. var caretPos = caret(input);
  1305. caret(input, caretPos.begin);
  1306. }, 0);
  1307. } else if (k == $.inputmask.keyCode.LEFT) {
  1308. setTimeout(function () {
  1309. var caretPos = caret(input);
  1310. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1311. }, 0);
  1312. }
  1313. }
  1314. var currentCaretPos = caret(input);
  1315. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), currentCaretPos.begin, opts);
  1316. handleOnKeyResult(input, keydownResult, currentCaretPos);
  1317. ignorable = $.inArray(k, opts.ignorables) != -1;
  1318. }
  1319. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  1320. var input = this, $input = $(input);
  1321. var k = e.which || e.charCode || e.keyCode;
  1322. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1323. return true;
  1324. } else {
  1325. if (k) {
  1326. //special treat the decimal separator
  1327. if (k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1328. var pos = checkval ? { begin: ndx, end: ndx } : caret(input), forwardPosition, c = String.fromCharCode(k);
  1329. //should we clear a possible selection??
  1330. var isSlctn = isSelection(pos.begin, pos.end);
  1331. if (isSlctn) {
  1332. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1333. handleRemove(input, $.inputmask.keyCode.DELETE, pos);
  1334. if (!opts.insertMode) { //preserve some space
  1335. opts.insertMode = !opts.insertMode;
  1336. setValidPosition(pos.begin, strict);
  1337. opts.insertMode = !opts.insertMode;
  1338. }
  1339. isSlctn = !opts.multi;
  1340. }
  1341. getMaskSet()["writeOutBuffer"] = true;
  1342. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1343. var valResult = isValid(p, c, strict);
  1344. if (valResult !== false) {
  1345. if (valResult !== true) {
  1346. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1347. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1348. }
  1349. resetMaskSet(true);
  1350. if (valResult.caret != undefined)
  1351. forwardPosition = valResult.caret;
  1352. else {
  1353. var vps = getMaskSet()["validPositions"];
  1354. if (!opts.keepStatic && (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation != undefined))
  1355. forwardPosition = p + 1;
  1356. else
  1357. forwardPosition = seekNext(p);
  1358. }
  1359. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1360. }
  1361. if (writeOut !== false) {
  1362. var self = this;
  1363. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  1364. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1365. var buffer = getBuffer();
  1366. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1367. if (checkval !== true) {
  1368. setTimeout(function () { //timeout needed for IE
  1369. if (isComplete(buffer) === true)
  1370. $input.trigger("complete");
  1371. skipInputEvent = true;
  1372. $input.trigger("input");
  1373. }, 0);
  1374. }
  1375. } else if (isSlctn) {
  1376. getMaskSet()["buffer"] = undefined;
  1377. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1378. }
  1379. } else if (isSlctn) {
  1380. getMaskSet()["buffer"] = undefined;
  1381. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1382. }
  1383. if (opts.showTooltip) { //update tooltip
  1384. $input.prop("title", getMaskSet()["mask"]);
  1385. }
  1386. if (checkval) {
  1387. var keyResult = opts.onKeyPress.call(this, e, getBuffer(), forwardPosition, opts);
  1388. if (keyResult && keyResult["refreshFromBuffer"]) {
  1389. handleOnKeyResult(input, keyResult);
  1390. if (keyResult.caret)
  1391. getMaskSet()["p"] = keyResult.caret;
  1392. }
  1393. } else {
  1394. var currentCaretPos = caret(input);
  1395. handleOnKeyResult(input, opts.onKeyPress.call(this, e, getBuffer(), currentCaretPos.begin, opts), currentCaretPos);
  1396. }
  1397. e.preventDefault();
  1398. }
  1399. }
  1400. }
  1401. function keyupEvent(e) {
  1402. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  1403. var currentCaretPos = caret(input);
  1404. var keyupResult = opts.onKeyUp.call(this, e, buffer, currentCaretPos.begin, opts);
  1405. handleOnKeyResult(input, keyupResult, currentCaretPos);
  1406. }
  1407. function pasteEvent(e) {
  1408. var input = this, $input = $(input), inputValue = input._valueGet(), caretPos = caret(input);
  1409. //paste event for IE8 and lower I guess ;-)
  1410. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1411. return true;
  1412. } else if (e.type == "paste") {
  1413. if (window.clipboardData && window.clipboardData.getData) { // IE
  1414. inputValue = inputValue.substr(0, caretPos.begin) + window.clipboardData.getData('Text') + inputValue.substr(caretPos.end, inputValue.length);
  1415. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  1416. inputValue = inputValue.substr(0, caretPos.begin) + e.originalEvent.clipboardData.getData('text/plain') + inputValue.substr(caretPos.end, inputValue.length);;
  1417. }
  1418. }
  1419. var pasteValue = $.isFunction(opts.onBeforePaste) ? (opts.onBeforePaste.call(input, inputValue, opts) || inputValue) : inputValue;
  1420. checkVal(input, true, false, isRTL ? pasteValue.split('').reverse() : pasteValue.split(''));
  1421. $input.click();
  1422. if (isComplete(getBuffer()) === true)
  1423. $input.trigger("complete");
  1424. return false;
  1425. }
  1426. function mobileInputEvent(e) {
  1427. var input = this;
  1428. //backspace in chrome32 only fires input event - detect & treat
  1429. var caretPos = caret(input),
  1430. currentValue = input._valueGet();
  1431. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1432. //correct caretposition for chrome
  1433. if (caretPos.begin > currentValue.length) {
  1434. caret(input, currentValue.length);
  1435. caretPos = caret(input);
  1436. }
  1437. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1438. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1439. && !isMask(caretPos.begin)) {
  1440. e.keyCode = $.inputmask.keyCode.BACKSPACE;
  1441. keydownEvent.call(input, e);
  1442. }
  1443. e.preventDefault();
  1444. }
  1445. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  1446. var input = this;
  1447. checkVal(input, true, false);
  1448. //var forwardPosition = getMaskSet()["p"];
  1449. //writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1450. if (isComplete(getBuffer()) === true)
  1451. $(input).trigger("complete");
  1452. e.preventDefault();
  1453. }
  1454. function compositionupdateEvent(e) { //fix for special latin-charset FF/Linux
  1455. //console.log(e.originalEvent.data + " vs " + compositionUpdateData);
  1456. var input = this;
  1457. setTimeout(function () {
  1458. caret(input, caret(input).begin - 1);
  1459. var keypress = $.Event("keypress");
  1460. keypress.which = e.originalEvent.data.charCodeAt(0);
  1461. skipKeyPressEvent = false;
  1462. ignorable = false;
  1463. keypressEvent.call(input, keypress, undefined, undefined, false);
  1464. var forwardPosition = getMaskSet()["p"];
  1465. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1466. }, 0);
  1467. return false;
  1468. }
  1469. function mask(el) {
  1470. $el = $(el);
  1471. if ($el.is(":input") && isInputTypeSupported($el.attr("type"))) {
  1472. //store tests & original buffer in the input element - used to get the unmasked value
  1473. $el.data('_inputmask', {
  1474. 'maskset': maskset,
  1475. 'opts': opts,
  1476. 'isRTL': false
  1477. });
  1478. //show tooltip
  1479. if (opts.showTooltip) {
  1480. $el.prop("title", getMaskSet()["mask"]);
  1481. }
  1482. if (el.dir == "rtl" || opts.rightAlign)
  1483. $el.css("text-align", "right");
  1484. if (el.dir == "rtl" || opts.numericInput) {
  1485. el.dir = "ltr";
  1486. $el.removeAttr("dir");
  1487. var inputData = $el.data('_inputmask');
  1488. inputData['isRTL'] = true;
  1489. $el.data('_inputmask', inputData);
  1490. isRTL = true;
  1491. }
  1492. //unbind all events - to make sure that no other mask will interfere when re-masking
  1493. $el.unbind(".inputmask");
  1494. //bind events
  1495. $el.closest('form').bind("submit", function (e) { //trigger change on submit if any
  1496. if (undoValue != getBuffer().join('')) {
  1497. $el.change();
  1498. }
  1499. if ($el[0]._valueGet && $el[0]._valueGet() == getBufferTemplate().join('')) {
  1500. $el[0]._valueSet(''); //clear masktemplete on submit and still has focus
  1501. }
  1502. if (opts.removeMaskOnSubmit) {
  1503. $el.inputmask("remove");
  1504. }
  1505. }).bind('reset', function () {
  1506. setTimeout(function () {
  1507. $el.trigger("setvalue");
  1508. }, 0);
  1509. });
  1510. $el.bind("mouseenter.inputmask", function () {
  1511. var $input = $(this), input = this;
  1512. if (!$input.is(":focus") && opts.showMaskOnHover) {
  1513. if (input._valueGet() != getBuffer().join('')) {
  1514. writeBuffer(input, getBuffer());
  1515. }
  1516. }
  1517. }).bind("blur.inputmask", function () {
  1518. var $input = $(this), input = this;
  1519. if ($input.data('_inputmask')) {
  1520. var nptValue = input._valueGet(), buffer = getBuffer().slice();
  1521. firstClick = true;
  1522. if (undoValue != buffer.join('')) {
  1523. $input.change();
  1524. undoValue = buffer.join('');
  1525. }
  1526. if (nptValue != '') {
  1527. if (opts.clearMaskOnLostFocus) {
  1528. if (nptValue == getBufferTemplate().join(''))
  1529. buffer = [];
  1530. else { //clearout optional tail of the mask
  1531. clearOptionalTail(buffer);
  1532. }
  1533. }
  1534. if (isComplete(buffer) === false) {
  1535. $input.trigger("incomplete");
  1536. if (opts.clearIncomplete) {
  1537. resetMaskSet();
  1538. if (opts.clearMaskOnLostFocus)
  1539. buffer = [];
  1540. else {
  1541. buffer = getBufferTemplate().slice();
  1542. }
  1543. }
  1544. }
  1545. if ($.isFunction(opts.postProcessOnBlur)) {
  1546. var keyResult = opts.postProcessOnBlur.call(input, buffer, opts);
  1547. if (keyResult) {
  1548. handleOnKeyResult(input, keyResult);
  1549. buffer = getBuffer();
  1550. }
  1551. }
  1552. writeBuffer(input, buffer);
  1553. }
  1554. }
  1555. }).bind("focus.inputmask", function (e) {
  1556. var $input = $(this), input = this, nptValue = input._valueGet();
  1557. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1558. if (input._valueGet() != getBuffer().join('')) {
  1559. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1560. }
  1561. }
  1562. undoValue = getBuffer().join('');
  1563. }).bind("mouseleave.inputmask", function () {
  1564. var $input = $(this), input = this;
  1565. if (opts.clearMaskOnLostFocus) {
  1566. var buffer = getBuffer().slice(), nptValue = input._valueGet();
  1567. if (!$input.is(":focus") && nptValue != $input.attr("placeholder") && nptValue != '') {
  1568. if (nptValue == getBufferTemplate().join(''))
  1569. buffer = [];
  1570. else { //clearout optional tail of the mask
  1571. clearOptionalTail(buffer);
  1572. }
  1573. writeBuffer(input, buffer);
  1574. }
  1575. }
  1576. }).bind("click.inputmask", function () {
  1577. var $input = $(this), input = this;
  1578. if ($input.is(":focus")) {
  1579. var selectedCaret = caret(input);
  1580. if (selectedCaret.begin == selectedCaret.end) {
  1581. if (opts.radixFocus && opts.radixPoint != "" && $.inArray(opts.radixPoint, getBuffer()) != -1 && (firstClick || getBuffer().join('') == getBufferTemplate().join(''))) {
  1582. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  1583. firstClick = false;
  1584. } else {
  1585. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1586. lastPosition = seekNext(getLastValidPosition(clickPosition));
  1587. if (clickPosition < lastPosition) {
  1588. caret(input, isMask(clickPosition) ? clickPosition : seekNext(clickPosition));
  1589. } else {
  1590. caret(input, lastPosition);
  1591. }
  1592. }
  1593. }
  1594. }
  1595. }).bind('dblclick.inputmask', function () {
  1596. var input = this;
  1597. setTimeout(function () {
  1598. caret(input, 0, seekNext(getLastValidPosition()));
  1599. }, 0);
  1600. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1601. ).bind('setvalue.inputmask', function () {
  1602. var input = this;
  1603. checkVal(input, true, false);
  1604. undoValue = getBuffer().join('');
  1605. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input._valueGet() == getBufferTemplate().join(''))
  1606. input._valueSet('');
  1607. }).bind('cut.inputmask', function (e) {
  1608. skipInputEvent = true; //stop inutFallback
  1609. var input = this, $input = $(input), pos = caret(input);
  1610. handleRemove(input, $.inputmask.keyCode.DELETE, pos);
  1611. var keypressResult = opts.onKeyPress.call(this, e, getBuffer(), getMaskSet()["p"], opts);
  1612. handleOnKeyResult(input, keypressResult, { begin: getMaskSet()["p"], end: getMaskSet()["p"] });
  1613. if (input._valueGet() == getBufferTemplate().join(''))
  1614. $input.trigger('cleared');
  1615. if (opts.showTooltip) { //update tooltip
  1616. $input.prop("title", getMaskSet()["mask"]);
  1617. }
  1618. }).bind('complete.inputmask', opts.oncomplete
  1619. ).bind('incomplete.inputmask', opts.onincomplete
  1620. ).bind('cleared.inputmask', opts.oncleared);
  1621. $el.bind("keydown.inputmask", keydownEvent
  1622. ).bind("keypress.inputmask", keypressEvent
  1623. ).bind("keyup.inputmask", keyupEvent
  1624. ).bind("compositionstart.inputmask", function (e) {
  1625. undoValue = getBuffer().join('');
  1626. //init compositionUpdateData
  1627. compositionUpdateData = "";
  1628. }).bind("compositionupdate.inputmask", compositionupdateEvent
  1629. ).bind("compositionend.inputmask", function (e) {
  1630. });
  1631. if (PasteEventType === "paste") {
  1632. $el.bind("input.inputmask", inputFallBackEvent);
  1633. }
  1634. //if (android || androidfirefox || androidchrome || kindle) {
  1635. // $el.unbind("input.inputmask");
  1636. // $el.bind("input.inputmask", mobileInputEvent);
  1637. //}
  1638. patchValueProperty(el);
  1639. //apply mask
  1640. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el._valueGet(), opts) || el._valueGet()) : el._valueGet();
  1641. checkVal(el, true, false, initialValue.split(''));
  1642. var buffer = getBuffer().slice();
  1643. undoValue = buffer.join('');
  1644. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1645. var activeElement;
  1646. try {
  1647. activeElement = document.activeElement;
  1648. } catch (e) {
  1649. }
  1650. if (isComplete(buffer) === false) {
  1651. if (opts.clearIncomplete)
  1652. resetMaskSet();
  1653. }
  1654. if (opts.clearMaskOnLostFocus) {
  1655. if (buffer.join('') == getBufferTemplate().join('')) {
  1656. buffer = [];
  1657. } else {
  1658. clearOptionalTail(buffer);
  1659. }
  1660. }
  1661. writeBuffer(el, buffer);
  1662. if (activeElement === el) { //position the caret when in focus
  1663. caret(el, seekNext(getLastValidPosition()));
  1664. }
  1665. installEventRuler(el);
  1666. }
  1667. }
  1668. //action object
  1669. if (actionObj != undefined) {
  1670. switch (actionObj["action"]) {
  1671. case "isComplete":
  1672. $el = $(actionObj["el"]);
  1673. maskset = $el.data('_inputmask')['maskset'];
  1674. opts = $el.data('_inputmask')['opts'];
  1675. return isComplete(actionObj["buffer"]);
  1676. case "unmaskedvalue":
  1677. $el = actionObj["$input"];
  1678. maskset = $el.data('_inputmask')['maskset'];
  1679. opts = $el.data('_inputmask')['opts'];
  1680. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1681. return unmaskedvalue(actionObj["$input"]);
  1682. case "mask":
  1683. undoValue = getBuffer().join('');
  1684. mask(actionObj["el"]);
  1685. break;
  1686. case "format":
  1687. $el = $({});
  1688. $el.data('_inputmask', {
  1689. 'maskset': maskset,
  1690. 'opts': opts,
  1691. 'isRTL': opts.numericInput
  1692. });
  1693. if (opts.numericInput) {
  1694. isRTL = true;
  1695. }
  1696. var valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj["value"], opts) || actionObj["value"]) : actionObj["value"]).split('');
  1697. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  1698. opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
  1699. if (actionObj["metadata"]) {
  1700. return {
  1701. value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''),
  1702. metadata: $el.inputmask("getmetadata")
  1703. }
  1704. }
  1705. return isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join('');
  1706. case "isValid":
  1707. $el = $({});
  1708. $el.data('_inputmask', {
  1709. 'maskset': maskset,
  1710. 'opts': opts,
  1711. 'isRTL': opts.numericInput
  1712. });
  1713. if (opts.numericInput) {
  1714. isRTL = true;
  1715. }
  1716. var valueBuffer = actionObj["value"].split('');
  1717. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1718. var buffer = getBuffer();
  1719. var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
  1720. for (; lmib > rl; lmib--) {
  1721. if (isMask(lmib)) break;
  1722. }
  1723. buffer.splice(rl, lmib + 1 - rl);
  1724. return isComplete(buffer) && actionObj["value"] == buffer.join('');
  1725. case "getemptymask":
  1726. $el = $(actionObj["el"]);
  1727. maskset = $el.data('_inputmask')['maskset'];
  1728. opts = $el.data('_inputmask')['opts'];
  1729. return getBufferTemplate();
  1730. case "remove":
  1731. var el = actionObj["el"];
  1732. $el = $(el);
  1733. maskset = $el.data('_inputmask')['maskset'];
  1734. opts = $el.data('_inputmask')['opts'];
  1735. //writeout the unmaskedvalue
  1736. el._valueSet(unmaskedvalue($el));
  1737. //unbind all events
  1738. $el.unbind(".inputmask");
  1739. //clear data
  1740. $el.removeData('_inputmask');
  1741. //restore the value property
  1742. var valueProperty;
  1743. if (Object.getOwnPropertyDescriptor)
  1744. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  1745. if (valueProperty && valueProperty.get) {
  1746. if (el._valueGet) {
  1747. Object.defineProperty(el, "value", {
  1748. get: el._valueGet,
  1749. set: el._valueSet
  1750. });
  1751. }
  1752. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  1753. if (el._valueGet) {
  1754. el.__defineGetter__("value", el._valueGet);
  1755. el.__defineSetter__("value", el._valueSet);
  1756. }
  1757. }
  1758. try { //try catch needed for IE7 as it does not supports deleting fns
  1759. delete el._valueGet;
  1760. delete el._valueSet;
  1761. } catch (e) {
  1762. el._valueGet = undefined;
  1763. el._valueSet = undefined;
  1764. }
  1765. break;
  1766. case "getmetadata":
  1767. $el = $(actionObj["el"]);
  1768. maskset = $el.data('_inputmask')['maskset'];
  1769. opts = $el.data('_inputmask')['opts'];
  1770. if ($.isArray(maskset["metadata"])) {
  1771. //find last alternation
  1772. var alternation, lvp = getLastValidPosition();
  1773. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  1774. if (getMaskSet()["validPositions"][firstAlt] && getMaskSet()["validPositions"][firstAlt].alternation != undefined) {
  1775. alternation = getMaskSet()["validPositions"][firstAlt].alternation;
  1776. break;
  1777. }
  1778. }
  1779. if (alternation != undefined) {
  1780. return maskset["metadata"][getMaskSet()["validPositions"][lvp].locator[alternation]];
  1781. } else return maskset["metadata"][0];
  1782. }
  1783. return maskset["metadata"];
  1784. }
  1785. }
  1786. }
  1787. $.inputmask = {
  1788. //options default
  1789. defaults: {
  1790. placeholder: "_",
  1791. optionalmarker: { start: "[", end: "]" },
  1792. quantifiermarker: { start: "{", end: "}" },
  1793. groupmarker: { start: "(", end: ")" },
  1794. alternatormarker: "|",
  1795. escapeChar: "\\",
  1796. mask: null,
  1797. oncomplete: $.noop, //executes when the mask is complete
  1798. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1799. oncleared: $.noop, //executes when the mask is cleared
  1800. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1801. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1802. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1803. removeMaskOnSubmit: false, //remove the mask before submitting the form.
  1804. clearMaskOnLostFocus: true,
  1805. insertMode: true, //insert the input or overwrite the input
  1806. clearIncomplete: false, //clear the incomplete input on blur
  1807. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1808. alias: null,
  1809. onKeyUp: $.noop, //callback to implement autocomplete on certain keys for example
  1810. onKeyPress: $.noop, //callback to implement autocomplete on certain keys for example
  1811. onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example
  1812. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1813. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1814. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1815. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1816. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1817. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1818. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1819. showTooltip: false, //show the activemask as tooltip
  1820. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1821. rightAlign: false, //align to the right
  1822. undoOnEscape: true, //pressing escape reverts the value to the value before focus
  1823. //numeric basic properties
  1824. radixPoint: "", //".", // | ","
  1825. radixFocus: false, //position caret to radixpoint on initial click
  1826. //numeric basic properties
  1827. nojumps: false, //do not jump over fixed parts in the mask
  1828. nojumpsThreshold: 0, //start nojumps as of
  1829. keepStatic: undefined, //try to keep the mask static while typing. Decisions to alter the mask will be posponed if possible - undefined see auto selection for multi masks
  1830. definitions: {
  1831. '9': {
  1832. validator: "[0-9]",
  1833. cardinality: 1,
  1834. definitionSymbol: "*"
  1835. },
  1836. 'a': {
  1837. validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  1838. cardinality: 1,
  1839. definitionSymbol: "*"
  1840. },
  1841. '*': {
  1842. validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  1843. cardinality: 1
  1844. }
  1845. },
  1846. //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1847. 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],
  1848. isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false
  1849. postProcessOnBlur: undefined //do some postprocessing of the value on the blur event, args => tmpBuffer, opts
  1850. },
  1851. keyCode: {
  1852. 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,
  1853. 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
  1854. },
  1855. masksCache: {},
  1856. escapeRegex: function (str) {
  1857. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1858. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1859. },
  1860. format: function (value, options, metadata) {
  1861. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1862. resolveAlias(opts.alias, options, opts);
  1863. return maskScope({ "action": "format", "value": value, "metadata": metadata }, generateMaskSet(opts), opts);
  1864. },
  1865. isValid: function (value, options) {
  1866. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1867. resolveAlias(opts.alias, options, opts);
  1868. return maskScope({ "action": "isValid", "value": value }, generateMaskSet(opts), opts);
  1869. }
  1870. };
  1871. $.fn.inputmask = function (fn, options, targetScope, targetData, msk) {
  1872. targetScope = targetScope || maskScope;
  1873. targetData = targetData || "_inputmask";
  1874. function importAttributeOptions(npt, opts, importedOptionsContainer) {
  1875. var $npt = $(npt);
  1876. if ($npt.data("inputmask-alias")) {
  1877. resolveAlias($npt.data("inputmask-alias"), {}, opts);
  1878. }
  1879. for (var option in opts) {
  1880. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  1881. if (optionData != undefined) {
  1882. if (option == "mask" && optionData.indexOf("[") == 0) {
  1883. opts[option] = optionData.replace(/[\s[\]]/g, "").split("','");
  1884. opts[option][0] = opts[option][0].replace("'", "");
  1885. opts[option][opts[option].length - 1] = opts[option][opts[option].length - 1].replace("'", "");
  1886. } else
  1887. opts[option] = typeof optionData == "boolean" ? optionData : optionData.toString();
  1888. if (importedOptionsContainer)
  1889. importedOptionsContainer[option] = opts[option];
  1890. }
  1891. }
  1892. return opts;
  1893. }
  1894. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1895. maskset;
  1896. if (typeof fn === "string") {
  1897. switch (fn) {
  1898. case "mask":
  1899. //resolve possible aliases given by options
  1900. resolveAlias(opts.alias, options, opts);
  1901. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1902. if (maskset == undefined) { return this; }
  1903. return this.each(function () {
  1904. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1905. });
  1906. case "unmaskedvalue":
  1907. var $input = $(this);
  1908. if ($input.data(targetData)) {
  1909. return targetScope({ "action": "unmaskedvalue", "$input": $input });
  1910. } else return $input.val();
  1911. case "remove":
  1912. return this.each(function () {
  1913. var $input = $(this);
  1914. if ($input.data(targetData)) {
  1915. targetScope({ "action": "remove", "el": this });
  1916. }
  1917. });
  1918. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1919. if (this.data(targetData)) {
  1920. return targetScope({ "action": "getemptymask", "el": this });
  1921. }
  1922. else return "";
  1923. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1924. return this.data(targetData) ? !this.data(targetData)['opts'].autoUnmask : false;
  1925. case "isComplete":
  1926. if (this.data(targetData)) {
  1927. return targetScope({ "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
  1928. } else return true;
  1929. case "getmetadata": //return mask metadata if exists
  1930. if (this.data(targetData)) {
  1931. return targetScope({ "action": "getmetadata", "el": this });
  1932. }
  1933. else return undefined;
  1934. case "_detectScope":
  1935. resolveAlias(opts.alias, options, opts);
  1936. if (msk != undefined && !resolveAlias(msk, options, opts) && $.inArray(msk, ["mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope"]) == -1) {
  1937. opts.mask = msk;
  1938. }
  1939. if ($.isFunction(opts.mask)) {
  1940. opts.mask = opts.mask.call(this, opts);
  1941. }
  1942. return $.isArray(opts.mask);
  1943. default:
  1944. resolveAlias(opts.alias, options, opts);
  1945. //check if the fn is an alias
  1946. if (!resolveAlias(fn, options, opts)) {
  1947. //maybe fn is a mask so we try
  1948. //set mask
  1949. opts.mask = fn;
  1950. }
  1951. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1952. if (maskset == undefined) { return this; }
  1953. return this.each(function () {
  1954. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1955. });
  1956. }
  1957. } else if (typeof fn == "object") {
  1958. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1959. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1960. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1961. if (maskset == undefined) { return this; }
  1962. return this.each(function () {
  1963. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1964. });
  1965. } else if (fn == undefined) {
  1966. //look for data-inputmask atribute - the attribute should only contain optipns
  1967. return this.each(function () {
  1968. var attrOptions = $(this).attr("data-inputmask");
  1969. if (attrOptions && attrOptions != "") {
  1970. try {
  1971. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1972. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1973. $.extend(true, dataoptions, options);
  1974. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1975. opts = importAttributeOptions(this, opts);
  1976. resolveAlias(opts.alias, dataoptions, opts);
  1977. opts.alias = undefined;
  1978. $(this).inputmask("mask", opts, targetScope);
  1979. } catch (ex) { } //need a more relax parseJSON
  1980. }
  1981. if ($(this).attr("data-inputmask-mask") || $(this).attr("data-inputmask-alias")) {
  1982. opts = $.extend(true, {}, $.inputmask.defaults, {});
  1983. var dataOptions = {};
  1984. opts = importAttributeOptions(this, opts, dataOptions);
  1985. resolveAlias(opts.alias, dataOptions, opts);
  1986. opts.alias = undefined;
  1987. $(this).inputmask("mask", opts, targetScope);
  1988. }
  1989. });
  1990. }
  1991. };
  1992. }
  1993. return $.fn.inputmask;
  1994. })(jQuery);