jquery.inputmask.js 96 KB

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