jquery.inputmask.js 90 KB

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