jquery.inputmask.js 114 KB

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