jquery.inputmask.js 90 KB

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