jquery.inputmask.js 114 KB

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