jquery.inputmask.js 90 KB

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