jquery.inputmask.js 117 KB

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