jquery.inputmask.js 96 KB

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