jquery.inputmask.js 97 KB

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