jquery.inputmask.js 96 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 == pos && match.matches == undefined) {
  422. matches.push({ "match": match, "locator": loopNdx.reverse() });
  423. return true;
  424. } else if (match.matches != undefined) {
  425. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  426. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  427. if (match) return true;
  428. } else if (match.isOptional) {
  429. var optionalToken = match;
  430. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  431. if (match) {
  432. var latestMatch = matches[matches.length - 1]["match"];
  433. var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
  434. if (isFirstMatch) {
  435. insertStop = true; //insert a stop for non greedy
  436. }
  437. testPos = pos; //match the position after the group
  438. }
  439. } else if (match.isAlternator) {
  440. var alternateToken = match;
  441. var currentMatches = matches.slice(), malternate1, malternate2, loopNdxCnt = loopNdx.length;
  442. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  443. if (altIndex == -1) {
  444. var currentPos = testPos;
  445. matches = [];
  446. match = ResolveTestFromToken(alternateToken.matches[0], ndxInitializer.slice(), [0].concat(loopNdx), quantifierRecurse);
  447. malternate1 = matches.slice();
  448. testPos = currentPos;
  449. matches = [];
  450. match = ResolveTestFromToken(alternateToken.matches[1], ndxInitializer, [1].concat(loopNdx), quantifierRecurse);
  451. malternate2 = matches.slice();
  452. //fuzzy merge matches
  453. matches = [];
  454. for (var ndx1 = 0; ndx1 < malternate1.length; ndx1++) {
  455. var altMatch = malternate1[ndx1]; currentMatches.push(altMatch);
  456. for (var ndx2 = 0; ndx2 < malternate2.length; ndx2++) {
  457. var altMatch2 = malternate2[ndx2];
  458. //verify equality
  459. if (altMatch.match.mask == altMatch2.match.mask) {
  460. malternate2.splice(ndx2, 1);
  461. altMatch.locator[loopNdxCnt] = -1;
  462. break;
  463. }
  464. }
  465. }
  466. matches = currentMatches.concat(malternate2);
  467. } else {
  468. match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  469. }
  470. if (match) return true;
  471. } else if (match.isQuantifier && quantifierRecurse !== true) {
  472. var qt = match;
  473. opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!)
  474. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  475. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  476. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  477. if (match) {
  478. //get latest match
  479. var latestMatch = matches[matches.length - 1]["match"];
  480. latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1;
  481. var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
  482. if (isFirstMatch) { //search for next possible match
  483. if (qndx > qt.quantifier.min - 1) {
  484. insertStop = true;
  485. testPos = pos; //match the position after the group
  486. break; //stop quantifierloop
  487. } else return true;
  488. } else {
  489. return true;
  490. }
  491. }
  492. }
  493. } else {
  494. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  495. if (match)
  496. return true;
  497. }
  498. } else testPos++;
  499. }
  500. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  501. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  502. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  503. if (match && testPos == pos) {
  504. return match;
  505. } else if (testPos > pos) {
  506. break;
  507. }
  508. }
  509. }
  510. }
  511. //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  512. // return getMaskSet()['tests'][pos];
  513. //}
  514. if (ndxIntlzr == undefined) {
  515. var previousPos = pos - 1, test;
  516. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  517. previousPos--;
  518. }
  519. if (test != undefined && previousPos > -1) {
  520. testPos = previousPos;
  521. ndxInitializer = test["locator"].slice();
  522. } else {
  523. previousPos = pos - 1;
  524. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  525. previousPos--;
  526. }
  527. if (test != undefined && previousPos > -1) {
  528. testPos = previousPos;
  529. ndxInitializer = test[0]["locator"].slice();
  530. }
  531. }
  532. }
  533. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  534. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  535. if ((match && testPos == pos) || testPos > pos) {
  536. break;
  537. }
  538. }
  539. if (matches.length == 0 || insertStop)
  540. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  541. getMaskSet()['tests'][pos] = matches;
  542. //console.log(pos + " - " + JSON.stringify(matches));
  543. return matches;
  544. }
  545. function getBufferTemplate() {
  546. if (getMaskSet()['_buffer'] == undefined) {
  547. //generate template
  548. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  549. }
  550. return getMaskSet()['_buffer'];
  551. }
  552. function getBuffer() {
  553. if (getMaskSet()['buffer'] == undefined) {
  554. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  555. }
  556. return getMaskSet()['buffer'];
  557. }
  558. function refreshFromBuffer(start, end) {
  559. var buffer = getBuffer().slice(); //work on clone
  560. if (start === true) {
  561. resetMaskSet();
  562. start = 0;
  563. end = buffer.length;
  564. } else {
  565. for (var i = start; i < end; i++) {
  566. delete getMaskSet()["validPositions"][i];
  567. delete getMaskSet()["tests"][i];
  568. }
  569. }
  570. for (var i = start; i < end; i++) {
  571. if (buffer[i] != opts.skipOptionalPartCharacter) {
  572. isValid(i, buffer[i], true, true);
  573. }
  574. }
  575. }
  576. function casing(elem, test) {
  577. switch (test.casing) {
  578. case "upper":
  579. elem = elem.toUpperCase();
  580. break;
  581. case "lower":
  582. elem = elem.toLowerCase();
  583. break;
  584. }
  585. return elem;
  586. }
  587. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  588. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  589. function _isValid(position, c, strict, fromSetValid) {
  590. var rslt = false;
  591. $.each(getTests(position), function (ndx, tst) {
  592. var test = tst["match"];
  593. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  594. for (var i = test.cardinality; i > loopend; i--) {
  595. chrs += getBufferElement(position - (i - 1));
  596. }
  597. if (c) {
  598. chrs += c;
  599. }
  600. //return is false or a json object => { pos: ??, c: ??} or true
  601. rslt = test.fn != null ?
  602. test.fn.test(chrs, getMaskSet(), position, strict, opts)
  603. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  604. { c: test["def"], pos: position }
  605. : false;
  606. if (rslt !== false) {
  607. var elem = rslt.c != undefined ? rslt.c : c;
  608. elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
  609. var validatedPos = position;
  610. if (rslt["remove"] != undefined) { //remove position
  611. stripValidPositions(rslt["remove"], rslt["remove"] + 1);
  612. }
  613. if (rslt["refreshFromBuffer"]) {
  614. var refresh = rslt["refreshFromBuffer"];
  615. strict = true;
  616. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
  617. if (rslt.pos == undefined && rslt.c == undefined) {
  618. rslt.pos = getLastValidPosition();
  619. return false;//breakout if refreshFromBuffer && nothing to insert
  620. }
  621. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  622. if (validatedPos != position) {
  623. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  624. return false;
  625. }
  626. } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
  627. validatedPos = rslt["pos"];
  628. refreshFromBuffer(position, validatedPos);
  629. if (validatedPos != position) {
  630. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  631. return false;
  632. }
  633. }
  634. if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
  635. return false; //breakout if nothing to insert
  636. }
  637. if (ndx > 0) {
  638. resetMaskSet(true);
  639. }
  640. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid))
  641. rslt = false;
  642. return false; //break from $.each
  643. }
  644. });
  645. return rslt;
  646. }
  647. //Check for a nonmask before the pos
  648. var buffer = getBuffer();
  649. for (var pndx = pos - 1; pndx > -1; pndx--) {
  650. if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx].fn == null)
  651. break;
  652. else if ((!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) {
  653. _isValid(pndx, buffer[pndx], true);
  654. break;
  655. }
  656. }
  657. var maskPos = pos;
  658. if (maskPos >= getMaskLength()) {
  659. // console.log("try alternate match");
  660. return false;
  661. }
  662. var result = _isValid(maskPos, c, strict, fromSetValid);
  663. if (!strict && result === false) {
  664. var currentPosValid = getMaskSet()["validPositions"][maskPos];
  665. if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
  666. result = { "caret": seekNext(maskPos) };
  667. } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
  668. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  669. result = _isValid(nPos, c, strict, fromSetValid);
  670. if (result !== false) {
  671. maskPos = nPos;
  672. break;
  673. }
  674. }
  675. }
  676. }
  677. if (result === true) result = { "pos": maskPos };
  678. return result;
  679. }
  680. function isMask(pos) {
  681. var test = getTest(pos);
  682. return test.fn != null ? test.fn : false;
  683. }
  684. function getMaskLength() {
  685. var maskLength;
  686. maxLength = $el.prop('maxLength');
  687. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  688. if (opts.greedy == false) {
  689. var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp],
  690. ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
  691. for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
  692. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  693. ndxIntlzr = testPos["locator"].slice();
  694. }
  695. maskLength = pos;
  696. } else
  697. maskLength = getBuffer().length;
  698. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  699. }
  700. function seekNext(pos) {
  701. var maskL = getMaskLength();
  702. if (pos >= maskL) return maskL;
  703. var position = pos;
  704. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
  705. }
  706. return position;
  707. }
  708. function seekPrevious(pos) {
  709. var position = pos;
  710. if (position <= 0) return 0;
  711. while (--position > 0 && !isMask(position)) {
  712. };
  713. return position;
  714. }
  715. function getBufferElement(position) {
  716. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  717. }
  718. function writeBuffer(input, buffer, caretPos) {
  719. input._valueSet(buffer.join(''));
  720. if (caretPos != undefined) {
  721. caret(input, caretPos);
  722. }
  723. }
  724. function getPlaceholder(pos, test) {
  725. test = test || getTest(pos);
  726. return test["placeholder"] || (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  727. }
  728. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  729. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  730. resetMaskSet();
  731. if (writeOut) input._valueSet(""); //initial clear
  732. $.each(inputValue, function (ndx, charCode) {
  733. if (intelliCheck === true) {
  734. var p = getMaskSet()["p"],
  735. lvp = p == -1 ? p : seekPrevious(p),
  736. pos = lvp == -1 ? ndx : seekNext(lvp);
  737. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
  738. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
  739. }
  740. } else {
  741. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
  742. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  743. }
  744. });
  745. if (writeOut) {
  746. var keypressResult = opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
  747. handleOnKeyResult(input, keypressResult);
  748. writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined);
  749. }
  750. }
  751. function escapeRegex(str) {
  752. return $.inputmask.escapeRegex.call(this, str);
  753. }
  754. function truncateInput(inputValue) {
  755. return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
  756. }
  757. function unmaskedvalue($input) {
  758. if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
  759. var umValue = [], vps = getMaskSet()["validPositions"];
  760. for (var pndx in vps) {
  761. if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
  762. umValue.push(vps[pndx]["input"]);
  763. }
  764. }
  765. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  766. var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
  767. if ($.isFunction(opts.onUnMask)) {
  768. unmaskedValue = opts.onUnMask.call($input, bufferValue, unmaskedValue, opts);
  769. }
  770. return unmaskedValue;
  771. } else {
  772. return $input[0]._valueGet();
  773. }
  774. }
  775. function TranslatePosition(pos) {
  776. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  777. var bffrLght = getBuffer().length;
  778. pos = bffrLght - pos;
  779. }
  780. return pos;
  781. }
  782. function caret(input, begin, end) {
  783. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  784. if (typeof begin == 'number') {
  785. begin = TranslatePosition(begin);
  786. end = TranslatePosition(end);
  787. end = (typeof end == 'number') ? end : begin;
  788. //store caret for multi scope
  789. var data = $(npt).data('_inputmask') || {};
  790. data["caret"] = { "begin": begin, "end": end };
  791. $(npt).data('_inputmask', data);
  792. if (!$(npt).is(":visible")) {
  793. return;
  794. }
  795. npt.scrollLeft = npt.scrollWidth;
  796. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  797. if (npt.setSelectionRange) {
  798. npt.selectionStart = begin;
  799. npt.selectionEnd = end;
  800. } else if (npt.createTextRange) {
  801. range = npt.createTextRange();
  802. range.collapse(true);
  803. range.moveEnd('character', end);
  804. range.moveStart('character', begin);
  805. range.select();
  806. }
  807. } else {
  808. var data = $(npt).data('_inputmask');
  809. if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
  810. begin = data["caret"]["begin"];
  811. end = data["caret"]["end"];
  812. } else if (npt.setSelectionRange) {
  813. begin = npt.selectionStart;
  814. end = npt.selectionEnd;
  815. } else if (document.selection && document.selection.createRange) {
  816. range = document.selection.createRange();
  817. begin = 0 - range.duplicate().moveStart('character', -100000);
  818. end = begin + range.text.length;
  819. }
  820. begin = TranslatePosition(begin);
  821. end = TranslatePosition(end);
  822. return { "begin": begin, "end": end };
  823. }
  824. }
  825. function determineLastRequiredPosition(returnDefinition) {
  826. var buffer = getBuffer(), bl = buffer.length,
  827. pos, lvp = getLastValidPosition(), positions = {},
  828. ndxIntlzr = getMaskSet()["validPositions"][lvp] != undefined ? getMaskSet()["validPositions"][lvp]["locator"].slice() : undefined, testPos;
  829. for (pos = lvp + 1; pos < buffer.length; pos++) {
  830. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  831. ndxIntlzr = testPos["locator"].slice();
  832. positions[pos] = $.extend(true, {}, testPos);
  833. }
  834. for (pos = bl - 1; pos > lvp; pos--) {
  835. testPos = positions[pos]["match"];
  836. if ((testPos.optionality || testPos.optionalQuantifier) && buffer[pos] == getPlaceholder(pos, testPos)) {
  837. bl--;
  838. } else break;
  839. }
  840. return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
  841. }
  842. function clearOptionalTail(input) {
  843. var buffer = getBuffer(), tmpBuffer = buffer.slice();
  844. var rl = determineLastRequiredPosition();
  845. tmpBuffer.length = rl;
  846. writeBuffer(input, tmpBuffer);
  847. }
  848. function isComplete(buffer) { //return true / false / undefined (repeat *)
  849. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  850. if (opts.repeat == "*") return undefined;
  851. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
  852. if (lvp == aml) {
  853. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
  854. complete = true;
  855. for (var i = 0; i <= aml; i++) {
  856. var mask = isMask(i);
  857. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  858. complete = false;
  859. break;
  860. }
  861. }
  862. }
  863. }
  864. return complete;
  865. }
  866. function isSelection(begin, end) {
  867. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  868. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  869. }
  870. function installEventRuler(npt) {
  871. var events = $._data(npt).events;
  872. $.each(events, function (eventType, eventHandlers) {
  873. $.each(eventHandlers, function (ndx, eventHandler) {
  874. if (eventHandler.namespace == "inputmask") {
  875. if (eventHandler.type != "setvalue") {
  876. var handler = eventHandler.handler;
  877. eventHandler.handler = function (e) {
  878. if (this.readOnly || this.disabled)
  879. e.preventDefault;
  880. else
  881. return handler.apply(this, arguments);
  882. };
  883. }
  884. }
  885. });
  886. });
  887. }
  888. function patchValueProperty(npt) {
  889. var valueGet;
  890. var valueSet;
  891. function PatchValhook(type) {
  892. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  893. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  894. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  895. elem.value = value;
  896. return elem;
  897. };
  898. $.valHooks[type] = {
  899. get: function (elem) {
  900. var $elem = $(elem);
  901. if ($elem.data('_inputmask')) {
  902. if ($elem.data('_inputmask')['opts'].autoUnmask)
  903. return $elem.inputmask('unmaskedvalue');
  904. else {
  905. var result = valueGet(elem),
  906. inputData = $elem.data('_inputmask'),
  907. maskset = inputData['maskset'],
  908. bufferTemplate = maskset['_buffer'];
  909. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  910. return result != bufferTemplate ? result : '';
  911. }
  912. } else return valueGet(elem);
  913. },
  914. set: function (elem, value) {
  915. var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
  916. if (inputData) {
  917. result = valueSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
  918. $elem.triggerHandler('setvalue.inputmask');
  919. } else {
  920. result = valueSet(elem, value);
  921. }
  922. return result;
  923. },
  924. inputmaskpatch: true
  925. };
  926. }
  927. }
  928. function getter() {
  929. var $self = $(this), inputData = $(this).data('_inputmask');
  930. if (inputData) {
  931. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  932. } else return valueGet.call(this);
  933. }
  934. function setter(value) {
  935. var inputData = $(this).data('_inputmask');
  936. if (inputData) {
  937. valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
  938. $(this).triggerHandler('setvalue.inputmask');
  939. } else {
  940. valueSet.call(this, value);
  941. }
  942. }
  943. function InstallNativeValueSetFallback(npt) {
  944. $(npt).bind("mouseenter.inputmask", function (event) {
  945. var $input = $(this), input = this;
  946. if (input._valueGet() != getBuffer().join('')) {
  947. $input.trigger("setvalue");
  948. }
  949. });
  950. //!! the bound handlers are executed in the order they where bound
  951. //reorder the events
  952. var events = $._data(npt).events;
  953. var handlers = events["mouseover"];
  954. if (handlers) {
  955. var ourHandler = handlers[handlers.length - 1];
  956. for (var i = handlers.length - 1; i > 0; i--) {
  957. handlers[i] = handlers[i - 1];
  958. }
  959. handlers[0] = ourHandler;
  960. }
  961. }
  962. if (!npt._valueGet) {
  963. //var valueProperty;
  964. if (Object.getOwnPropertyDescriptor)
  965. var valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  966. if (valueProperty && valueProperty.configurable && false) { //experimental for chrome
  967. npt._value = valueProperty.value;
  968. valueGet = function () {
  969. return this._value || "";
  970. }
  971. valueSet = function (value) {
  972. this._value = value;
  973. this.select();
  974. this.setRangeText(value);
  975. this.selectionStart = this.selectionEnd;
  976. }
  977. Object.defineProperty(npt, "value", {
  978. get: getter,
  979. set: setter
  980. });
  981. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  982. valueGet = npt.__lookupGetter__("value");
  983. valueSet = npt.__lookupSetter__("value");
  984. npt.__defineGetter__("value", getter);
  985. npt.__defineSetter__("value", setter);
  986. } else { //jquery.val
  987. valueGet = function () { return npt.value; }
  988. valueSet = function (value) { npt.value = value; }
  989. PatchValhook(npt.type);
  990. InstallNativeValueSetFallback(npt);
  991. }
  992. npt._valueGet = function () {
  993. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  994. };
  995. npt._valueSet = function (value) {
  996. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  997. };
  998. }
  999. }
  1000. function handleRemove(input, k, pos) {
  1001. if (opts.numericInput || isRTL) {
  1002. if (k == opts.keyCode.BACKSPACE)
  1003. k = opts.keyCode.DELETE;
  1004. else if (k == opts.keyCode.DELETE)
  1005. k = opts.keyCode.BACKSPACE;
  1006. if (isRTL) {
  1007. var pend = pos.end;
  1008. pos.end = pos.begin;
  1009. pos.begin = pend;
  1010. }
  1011. }
  1012. if (k == opts.keyCode.BACKSPACE && pos.end - pos.begin <= 1)
  1013. pos.begin = seekPrevious(pos.begin);
  1014. else if (k == opts.keyCode.DELETE && pos.begin == pos.end)
  1015. pos.end++;
  1016. stripValidPositions(pos.begin, pos.end);
  1017. var firstMaskedPos = getLastValidPosition(pos.begin);
  1018. if (firstMaskedPos < pos.begin) {
  1019. getMaskSet()["p"] = seekNext(firstMaskedPos);
  1020. } else {
  1021. getMaskSet()["p"] = pos.begin;
  1022. }
  1023. }
  1024. function handleOnKeyResult(input, keyResult, caretPos) {
  1025. if (keyResult && keyResult["refreshFromBuffer"]) {
  1026. var refresh = keyResult["refreshFromBuffer"];
  1027. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
  1028. resetMaskSet(true);
  1029. if (caretPos != undefined) {
  1030. writeBuffer(input, getBuffer());
  1031. caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
  1032. }
  1033. }
  1034. }
  1035. function keydownEvent(e) {
  1036. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1037. skipKeyPressEvent = false;
  1038. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1039. //backspace, delete, and escape get special treatment
  1040. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  1041. e.preventDefault(); //stop default action but allow propagation
  1042. if (k == 88) valueOnFocus = getBuffer().join('');
  1043. handleRemove(input, k, pos);
  1044. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  1045. if (input._valueGet() == getBufferTemplate().join(''))
  1046. $input.trigger('cleared');
  1047. if (opts.showTooltip) { //update tooltip
  1048. $input.prop("title", getMaskSet()["mask"]);
  1049. }
  1050. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1051. setTimeout(function () {
  1052. var caretPos = seekNext(getLastValidPosition());
  1053. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1054. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1055. }, 0);
  1056. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  1057. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1058. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  1059. checkVal(input, true, false, valueOnFocus.split(''));
  1060. $input.click();
  1061. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1062. opts.insertMode = !opts.insertMode;
  1063. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1064. } else if (opts.insertMode == false && !e.shiftKey) {
  1065. if (k == opts.keyCode.RIGHT) {
  1066. setTimeout(function () {
  1067. var caretPos = caret(input);
  1068. caret(input, caretPos.begin);
  1069. }, 0);
  1070. } else if (k == opts.keyCode.LEFT) {
  1071. setTimeout(function () {
  1072. var caretPos = caret(input);
  1073. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1074. }, 0);
  1075. }
  1076. }
  1077. var currentCaretPos = caret(input);
  1078. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), currentCaretPos.begin, opts);
  1079. handleOnKeyResult(input, keydownResult, currentCaretPos);
  1080. ignorable = $.inArray(k, opts.ignorables) != -1;
  1081. }
  1082. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  1083. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1084. if (k == undefined && skipKeyPressEvent) return false;
  1085. skipKeyPressEvent = true;
  1086. var input = this, $input = $(input);
  1087. e = e || window.event;
  1088. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  1089. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1090. return true;
  1091. } else {
  1092. if (k) {
  1093. //special treat the decimal separator
  1094. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1095. var pos, forwardPosition, c = String.fromCharCode(k);
  1096. if (checkval) {
  1097. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  1098. pos = { begin: pcaret, end: pcaret };
  1099. } else {
  1100. pos = caret(input);
  1101. }
  1102. //should we clear a possible selection??
  1103. var isSlctn = isSelection(pos.begin, pos.end);
  1104. if (isSlctn) {
  1105. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1106. handleRemove(input, opts.keyCode.DELETE, pos);
  1107. if (!opts.insertMode) { //preserve some space
  1108. opts.insertMode = !opts.insertMode;
  1109. setValidPosition(pos.begin, strict);
  1110. opts.insertMode = !opts.insertMode;
  1111. }
  1112. isSlctn = !opts.multi;
  1113. }
  1114. getMaskSet()["writeOutBuffer"] = true;
  1115. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1116. var valResult = isValid(p, c, strict);
  1117. if (valResult !== false) {
  1118. if (valResult !== true) {
  1119. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1120. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1121. }
  1122. resetMaskSet(true);
  1123. if (valResult.caret != undefined)
  1124. forwardPosition = valResult.caret;
  1125. else {
  1126. var vps = getMaskSet()["validPositions"];
  1127. if (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1)
  1128. forwardPosition = p + 1;
  1129. else
  1130. forwardPosition = seekNext(p);
  1131. }
  1132. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1133. }
  1134. if (writeOut !== false) {
  1135. var self = this;
  1136. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  1137. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1138. var buffer = getBuffer();
  1139. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1140. if (checkval !== true) {
  1141. setTimeout(function () { //timeout needed for IE
  1142. if (isComplete(buffer) === true)
  1143. $input.trigger("complete");
  1144. skipInputEvent = true;
  1145. $input.trigger("input");
  1146. }, 0);
  1147. }
  1148. } else if (isSlctn) {
  1149. getMaskSet()["buffer"] = undefined;
  1150. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1151. }
  1152. } else if (isSlctn) {
  1153. getMaskSet()["buffer"] = undefined;
  1154. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1155. }
  1156. if (opts.showTooltip) { //update tooltip
  1157. $input.prop("title", getMaskSet()["mask"]);
  1158. }
  1159. //needed for IE8 and below
  1160. if (e && checkval != true) {
  1161. e.preventDefault ? e.preventDefault() : e.returnValue = false;
  1162. var currentCaretPos = caret(input);
  1163. var keypressResult = opts.onKeyPress.call(this, e, getBuffer(), currentCaretPos.begin, opts);
  1164. handleOnKeyResult(input, keypressResult, currentCaretPos);
  1165. }
  1166. var temp;
  1167. for (var i in getMaskSet().validPositions) {
  1168. temp += " " + i;
  1169. }
  1170. }
  1171. }
  1172. }
  1173. function keyupEvent(e) {
  1174. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  1175. var currentCaretPos = caret(input);
  1176. var keyupResult = opts.onKeyUp.call(this, e, buffer, currentCaretPos.begin, opts);
  1177. handleOnKeyResult(input, keyupResult, currentCaretPos);
  1178. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  1179. if ($input.hasClass('focus-inputmask') && input._valueGet().length == 0) {
  1180. resetMaskSet();
  1181. buffer = getBuffer();
  1182. writeBuffer(input, buffer);
  1183. caret(input, 0);
  1184. valueOnFocus = getBuffer().join('');
  1185. } else {
  1186. writeBuffer(input, buffer);
  1187. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  1188. }
  1189. }
  1190. }
  1191. function pasteEvent(e) {
  1192. if (skipInputEvent === true && e.type == "input") {
  1193. skipInputEvent = false;
  1194. return true;
  1195. }
  1196. var input = this, $input = $(input), inputValue = input._valueGet();
  1197. //paste event for IE8 and lower I guess ;-)
  1198. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1199. return true;
  1200. } else if (e.type == "paste") {
  1201. if (window.clipboardData && window.clipboardData.getData) { // IE
  1202. inputValue = window.clipboardData.getData('Text');
  1203. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  1204. inputValue = e.originalEvent.clipboardData.getData('text/plain');
  1205. }
  1206. }
  1207. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, inputValue, opts) : inputValue;
  1208. checkVal(input, true, false, pasteValue.split(''), true);
  1209. $input.click();
  1210. if (isComplete(getBuffer()) === true)
  1211. $input.trigger("complete");
  1212. return false;
  1213. }
  1214. function mobileInputEvent(e) {
  1215. if (skipInputEvent === true && e.type == "input") {
  1216. skipInputEvent = false;
  1217. return true;
  1218. }
  1219. var input = this;
  1220. //backspace in chrome32 only fires input event - detect & treat
  1221. var caretPos = caret(input),
  1222. currentValue = input._valueGet();
  1223. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1224. //correct caretposition for chrome
  1225. if (caretPos.begin > currentValue.length) {
  1226. caret(input, currentValue.length);
  1227. caretPos = caret(input);
  1228. }
  1229. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1230. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1231. && !isMask(caretPos.begin)) {
  1232. e.keyCode = opts.keyCode.BACKSPACE;
  1233. keydownEvent.call(input, e);
  1234. }
  1235. e.preventDefault();
  1236. }
  1237. function mask(el) {
  1238. $el = $(el);
  1239. if ($el.is(":input") && $el.attr("type") != "number") {
  1240. //store tests & original buffer in the input element - used to get the unmasked value
  1241. $el.data('_inputmask', {
  1242. 'maskset': maskset,
  1243. 'opts': opts,
  1244. 'isRTL': false
  1245. });
  1246. //show tooltip
  1247. if (opts.showTooltip) {
  1248. $el.prop("title", getMaskSet()["mask"]);
  1249. }
  1250. if (el.dir == "rtl" || opts.rightAlign)
  1251. $el.css("text-align", "right");
  1252. if (el.dir == "rtl" || opts.numericInput) {
  1253. el.dir = "ltr";
  1254. $el.removeAttr("dir");
  1255. var inputData = $el.data('_inputmask');
  1256. inputData['isRTL'] = true;
  1257. $el.data('_inputmask', inputData);
  1258. isRTL = true;
  1259. }
  1260. //unbind all events - to make sure that no other mask will interfere when re-masking
  1261. $el.unbind(".inputmask");
  1262. $el.removeClass('focus-inputmask');
  1263. //bind events
  1264. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1265. if (valueOnFocus != getBuffer().join('')) {
  1266. $el.change();
  1267. }
  1268. if (opts.autoUnmask && opts.removeMaskOnSubmit) {
  1269. $el.inputmask("remove");
  1270. }
  1271. }).bind('reset', function () {
  1272. setTimeout(function () {
  1273. $el.trigger("setvalue");
  1274. }, 0);
  1275. });
  1276. $el.bind("mouseenter.inputmask", function () {
  1277. var $input = $(this), input = this;
  1278. if (!$input.hasClass('focus-inputmask') && opts.showMaskOnHover) {
  1279. if (input._valueGet() != getBuffer().join('')) {
  1280. writeBuffer(input, getBuffer());
  1281. }
  1282. }
  1283. }).bind("blur.inputmask", function () {
  1284. var $input = $(this), input = this;
  1285. if ($input.data('_inputmask')) {
  1286. var nptValue = input._valueGet(), buffer = getBuffer();
  1287. $input.removeClass('focus-inputmask');
  1288. if (valueOnFocus != getBuffer().join('')) {
  1289. $input.change();
  1290. }
  1291. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1292. if (nptValue == getBufferTemplate().join(''))
  1293. input._valueSet('');
  1294. else { //clearout optional tail of the mask
  1295. clearOptionalTail(input);
  1296. }
  1297. }
  1298. if (isComplete(buffer) === false) {
  1299. $input.trigger("incomplete");
  1300. if (opts.clearIncomplete) {
  1301. resetMaskSet();
  1302. if (opts.clearMaskOnLostFocus)
  1303. input._valueSet('');
  1304. else {
  1305. buffer = getBufferTemplate().slice();
  1306. writeBuffer(input, buffer);
  1307. }
  1308. }
  1309. }
  1310. }
  1311. }).bind("focus.inputmask", function () {
  1312. var $input = $(this), input = this, nptValue = input._valueGet();
  1313. if (opts.showMaskOnFocus && !$input.hasClass('focus-inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1314. if (input._valueGet() != getBuffer().join('')) {
  1315. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1316. }
  1317. }
  1318. $input.addClass('focus-inputmask');
  1319. valueOnFocus = getBuffer().join('');
  1320. }).bind("mouseleave.inputmask", function () {
  1321. var $input = $(this), input = this;
  1322. if (opts.clearMaskOnLostFocus) {
  1323. if (!$input.hasClass('focus-inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1324. if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
  1325. input._valueSet('');
  1326. else { //clearout optional tail of the mask
  1327. clearOptionalTail(input);
  1328. }
  1329. }
  1330. }
  1331. }).bind("click.inputmask", function () {
  1332. var input = this;
  1333. if ($(input).is(":focus")) {
  1334. setTimeout(function () {
  1335. var selectedCaret = caret(input);
  1336. if (selectedCaret.begin == selectedCaret.end) {
  1337. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1338. lvp = getLastValidPosition(clickPosition),
  1339. lastPosition = seekNext(lvp);
  1340. if (clickPosition < lastPosition) {
  1341. if (isMask(clickPosition))
  1342. caret(input, clickPosition);
  1343. else caret(input, seekNext(clickPosition));
  1344. } else
  1345. caret(input, lastPosition);
  1346. }
  1347. }, 0);
  1348. }
  1349. }).bind('dblclick.inputmask', function () {
  1350. var input = this;
  1351. setTimeout(function () {
  1352. caret(input, 0, seekNext(getLastValidPosition()));
  1353. }, 0);
  1354. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1355. ).bind('setvalue.inputmask', function () {
  1356. var input = this;
  1357. checkVal(input, true);
  1358. valueOnFocus = getBuffer().join('');
  1359. }).bind('complete.inputmask', opts.oncomplete
  1360. ).bind('incomplete.inputmask', opts.onincomplete
  1361. ).bind('cleared.inputmask', opts.oncleared);
  1362. $el.bind("keydown.inputmask", keydownEvent
  1363. ).bind("keypress.inputmask", keypressEvent
  1364. ).bind("keyup.inputmask", keyupEvent);
  1365. if (android || androidfirefox || androidchrome || kindle) {
  1366. if (PasteEventType == "input") {
  1367. $el.unbind(PasteEventType + ".inputmask");
  1368. }
  1369. $el.bind("input.inputmask", mobileInputEvent);
  1370. }
  1371. if (msie1x)
  1372. $el.bind("input.inputmask", pasteEvent);
  1373. patchValueProperty(el);
  1374. //apply mask
  1375. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1376. checkVal(el, true, false, initialValue.split(''), true);
  1377. valueOnFocus = getBuffer().join('');
  1378. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1379. var activeElement;
  1380. try {
  1381. activeElement = document.activeElement;
  1382. } catch (e) {
  1383. }
  1384. if (isComplete(getBuffer()) === false) {
  1385. if (opts.clearIncomplete)
  1386. resetMaskSet();
  1387. }
  1388. if (opts.clearMaskOnLostFocus) {
  1389. if (getBuffer().join('') == getBufferTemplate().join('')) {
  1390. el._valueSet('');
  1391. } else {
  1392. clearOptionalTail(el);
  1393. }
  1394. } else {
  1395. writeBuffer(el, getBuffer());
  1396. }
  1397. if (activeElement === el) { //position the caret when in focus
  1398. $el.addClass('focus-inputmask');
  1399. caret(el, seekNext(getLastValidPosition()));
  1400. }
  1401. installEventRuler(el);
  1402. }
  1403. }
  1404. //action object
  1405. if (actionObj != undefined) {
  1406. switch (actionObj["action"]) {
  1407. case "isComplete":
  1408. $el = $(actionObj["el"]);
  1409. maskset = $el.data('_inputmask')['maskset'];
  1410. opts = $el.data('_inputmask')['opts'];
  1411. return isComplete(actionObj["buffer"]);
  1412. case "unmaskedvalue":
  1413. $el = actionObj["$input"];
  1414. maskset = $el.data('_inputmask')['maskset'];
  1415. opts = $el.data('_inputmask')['opts'];
  1416. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1417. return unmaskedvalue(actionObj["$input"]);
  1418. case "mask":
  1419. valueOnFocus = getBuffer().join('');
  1420. mask(actionObj["el"]);
  1421. break;
  1422. case "format":
  1423. $el = $({});
  1424. $el.data('_inputmask', {
  1425. 'maskset': maskset,
  1426. 'opts': opts,
  1427. 'isRTL': opts.numericInput
  1428. });
  1429. if (opts.numericInput) {
  1430. isRTL = true;
  1431. }
  1432. var valueBuffer = actionObj["value"].split('');
  1433. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer, true);
  1434. opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
  1435. return isRTL ? getBuffer().reverse().join('') : getBuffer().join('');
  1436. case "isValid":
  1437. $el = $({});
  1438. $el.data('_inputmask', {
  1439. 'maskset': maskset,
  1440. 'opts': opts,
  1441. 'isRTL': opts.numericInput
  1442. });
  1443. if (opts.numericInput) {
  1444. isRTL = true;
  1445. }
  1446. var valueBuffer = actionObj["value"].split('');
  1447. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1448. var buffer = getBuffer();
  1449. var rl = determineLastRequiredPosition();
  1450. buffer.length = rl;
  1451. return isComplete(buffer) && actionObj["value"] == buffer.join('');
  1452. case "getemptymask":
  1453. $el = $(actionObj["el"]);
  1454. maskset = $el.data('_inputmask')['maskset'];
  1455. opts = $el.data('_inputmask')['opts'];
  1456. return getBufferTemplate();
  1457. case "remove":
  1458. var el = actionObj["el"];
  1459. $el = $(el);
  1460. maskset = $el.data('_inputmask')['maskset'];
  1461. opts = $el.data('_inputmask')['opts'];
  1462. //writeout the unmaskedvalue
  1463. el._valueSet(unmaskedvalue($el));
  1464. //unbind all events
  1465. $el.unbind(".inputmask");
  1466. $el.removeClass('focus-inputmask');
  1467. //clear data
  1468. $el.removeData('_inputmask');
  1469. //restore the value property
  1470. var valueProperty;
  1471. if (Object.getOwnPropertyDescriptor)
  1472. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  1473. if (valueProperty && valueProperty.get) {
  1474. if (el._valueGet) {
  1475. Object.defineProperty(el, "value", {
  1476. get: el._valueGet,
  1477. set: el._valueSet
  1478. });
  1479. }
  1480. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  1481. if (el._valueGet) {
  1482. el.__defineGetter__("value", el._valueGet);
  1483. el.__defineSetter__("value", el._valueSet);
  1484. }
  1485. }
  1486. try { //try catch needed for IE7 as it does not supports deleting fns
  1487. delete el._valueGet;
  1488. delete el._valueSet;
  1489. } catch (e) {
  1490. el._valueGet = undefined;
  1491. el._valueSet = undefined;
  1492. }
  1493. break;
  1494. }
  1495. }
  1496. };
  1497. $.inputmask = {
  1498. //options default
  1499. defaults: {
  1500. placeholder: "_",
  1501. optionalmarker: { start: "[", end: "]" },
  1502. quantifiermarker: { start: "{", end: "}" },
  1503. groupmarker: { start: "(", end: ")" },
  1504. alternatormarker: "|",
  1505. escapeChar: "\\",
  1506. mask: null,
  1507. oncomplete: $.noop, //executes when the mask is complete
  1508. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1509. oncleared: $.noop, //executes when the mask is cleared
  1510. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1511. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1512. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1513. removeMaskOnSubmit: true, //remove the mask before submitting the form. Use in combination with autoUnmask: true
  1514. clearMaskOnLostFocus: true,
  1515. insertMode: true, //insert the input or overwrite the input
  1516. clearIncomplete: false, //clear the incomplete input on blur
  1517. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1518. alias: null,
  1519. onKeyUp: $.noop, //callback to implement autocomplete on certain keys for example
  1520. onKeyPress: $.noop, //callback to implement autocomplete on certain keys for example
  1521. onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example
  1522. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1523. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1524. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1525. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1526. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1527. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1528. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1529. showTooltip: false, //show the activemask as tooltip
  1530. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1531. rightAlign: false, //align to the right
  1532. //numeric basic properties
  1533. radixPoint: "", //".", // | ","
  1534. //numeric basic properties
  1535. nojumps: false, //do not jump over fixed parts in the mask
  1536. nojumpsThreshold: 0, //start nojumps as of
  1537. definitions: {
  1538. '9': {
  1539. validator: "[0-9]",
  1540. cardinality: 1,
  1541. definitionSymbol: "*"
  1542. },
  1543. 'a': {
  1544. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1545. cardinality: 1,
  1546. definitionSymbol: "*"
  1547. },
  1548. '*': {
  1549. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1550. cardinality: 1
  1551. }
  1552. },
  1553. keyCode: {
  1554. 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,
  1555. 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
  1556. },
  1557. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1558. 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],
  1559. isComplete: undefined //override for isComplete - args => buffer, opts - return true || false
  1560. },
  1561. masksCache: {},
  1562. escapeRegex: function (str) {
  1563. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1564. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1565. },
  1566. format: function (value, options) {
  1567. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1568. resolveAlias(opts.alias, options, opts);
  1569. return maskScope({ "action": "format", "value": value }, generateMaskSet(opts), opts);
  1570. },
  1571. isValid: function (value, options) {
  1572. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1573. resolveAlias(opts.alias, options, opts);
  1574. return maskScope({ "action": "isValid", "value": value }, generateMaskSet(opts), opts);
  1575. }
  1576. };
  1577. $.fn.inputmask = function (fn, options, targetScope, targetData, msk) {
  1578. targetScope = targetScope || maskScope;
  1579. targetData = targetData || "_inputmask";
  1580. function importAttributeOptions(npt, opts) {
  1581. var $npt = $(npt);
  1582. for (var option in opts) {
  1583. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  1584. if (optionData != undefined)
  1585. opts[option] = optionData;
  1586. }
  1587. return opts;
  1588. }
  1589. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1590. maskset;
  1591. if (typeof fn === "string") {
  1592. switch (fn) {
  1593. case "mask":
  1594. //resolve possible aliases given by options
  1595. resolveAlias(opts.alias, options, opts);
  1596. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1597. if (maskset.length == 0) { return this; }
  1598. return this.each(function () {
  1599. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1600. });
  1601. case "unmaskedvalue":
  1602. var $input = $(this);
  1603. if ($input.data(targetData)) {
  1604. return targetScope({ "action": "unmaskedvalue", "$input": $input });
  1605. } else return $input.val();
  1606. case "remove":
  1607. return this.each(function () {
  1608. var $input = $(this);
  1609. if ($input.data(targetData)) {
  1610. targetScope({ "action": "remove", "el": this });
  1611. }
  1612. });
  1613. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1614. if (this.data(targetData)) {
  1615. return targetScope({ "action": "getemptymask", "el": this });
  1616. }
  1617. else return "";
  1618. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1619. return this.data(targetData) ? !this.data(targetData)['opts'].autoUnmask : false;
  1620. case "isComplete":
  1621. if (this.data(targetData)) {
  1622. return targetScope({ "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
  1623. } else return true;
  1624. case "getmetadata": //return mask metadata if exists
  1625. if (this.data(targetData)) {
  1626. maskset = this.data(targetData)['maskset'];
  1627. return maskset['metadata'];
  1628. }
  1629. else return undefined;
  1630. case "_detectScope":
  1631. resolveAlias(opts.alias, options, opts);
  1632. if (msk != undefined && !resolveAlias(msk, options, opts) && $.inArray(msk, ["mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope"]) == -1) {
  1633. opts.mask = msk;
  1634. }
  1635. if ($.isFunction(opts.mask)) {
  1636. opts.mask = opts.mask.call(this, opts);
  1637. }
  1638. return $.isArray(opts.mask);
  1639. default:
  1640. resolveAlias(opts.alias, options, opts);
  1641. //check if the fn is an alias
  1642. if (!resolveAlias(fn, options, opts)) {
  1643. //maybe fn is a mask so we try
  1644. //set mask
  1645. opts.mask = fn;
  1646. }
  1647. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1648. if (maskset == undefined) { return this; }
  1649. return this.each(function () {
  1650. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1651. });
  1652. }
  1653. } else if (typeof fn == "object") {
  1654. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1655. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1656. maskset = generateMaskSet(opts, targetScope !== maskScope);
  1657. if (maskset == undefined) { return this; }
  1658. return this.each(function () {
  1659. targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
  1660. });
  1661. } else if (fn == undefined) {
  1662. //look for data-inputmask atribute - the attribute should only contain optipns
  1663. return this.each(function () {
  1664. var attrOptions = $(this).attr("data-inputmask");
  1665. if (attrOptions && attrOptions != "") {
  1666. try {
  1667. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1668. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1669. $.extend(true, dataoptions, options);
  1670. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1671. resolveAlias(opts.alias, dataoptions, opts);
  1672. opts.alias = undefined;
  1673. $(this).inputmask("mask", opts, targetScope);
  1674. } catch (ex) { } //need a more relax parseJSON
  1675. }
  1676. });
  1677. }
  1678. };
  1679. }
  1680. }));