jquery.inputmask.js 84 KB

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