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 msie1x = typeof ScriptEngineMajorVersion === "function" ? ScriptEngineMajorVersion() >= 10 : /*@cc_on (@_jscript_version >= 10) ||@*/false, //IEx detection
  295. ua = navigator.userAgent,
  296. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  297. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  298. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  299. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  300. 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),
  301. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  302. //if (androidchrome) {
  303. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  304. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  305. // androidchrome32 = (version == 32);
  306. //}
  307. //masking scope
  308. //actionObj definition see below
  309. function maskScope(actionObj, maskset, opts) {
  310. var isRTL = false,
  311. valueOnFocus,
  312. $el,
  313. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  314. skipInputEvent = false, //skip when triggered from within inputmask
  315. ignorable = false,
  316. maxLength,
  317. firstClick = true;
  318. //maskset helperfunctions
  319. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  320. minimalPos = minimalPos || 0;
  321. var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos;
  322. do {
  323. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  324. var validPos = getMaskSet()['validPositions'][pos];
  325. test = validPos["match"];
  326. ndxIntlzr = validPos["locator"].slice();
  327. maskTemplate.push(includeInput === true ? validPos["input"] : getPlaceholder(pos, test));
  328. } else {
  329. if (minimalPos > pos) {
  330. var testPositions = getTests(pos, ndxIntlzr, pos - 1);
  331. testPos = testPositions[0];
  332. } else {
  333. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  334. }
  335. test = testPos["match"];
  336. ndxIntlzr = testPos["locator"].slice();
  337. maskTemplate.push(getPlaceholder(pos, test));
  338. }
  339. pos++;
  340. } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  341. maskTemplate.pop(); //drop the last one which is empty
  342. return maskTemplate;
  343. }
  344. function getMaskSet() {
  345. return maskset;
  346. }
  347. function resetMaskSet(soft) {
  348. var maskset = getMaskSet();
  349. maskset["buffer"] = undefined;
  350. maskset["tests"] = {};
  351. if (soft !== true) {
  352. maskset["_buffer"] = undefined;
  353. maskset["validPositions"] = {};
  354. maskset["p"] = 0;
  355. }
  356. }
  357. function getLastValidPosition(closestTo) {
  358. var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset["validPositions"];
  359. if (closestTo == undefined) closestTo = -1;
  360. var before = lastValidPosition, after = lastValidPosition;
  361. for (var posNdx in valids) {
  362. var psNdx = parseInt(posNdx);
  363. if (closestTo == -1 || valids[psNdx]["match"].fn != null) {
  364. if (psNdx <= closestTo) before = psNdx;
  365. if (psNdx >= closestTo) after = psNdx;
  366. }
  367. }
  368. lastValidPosition = (closestTo - before) > 1 || after < closestTo ? before : after;
  369. return lastValidPosition;
  370. }
  371. function setValidPosition(pos, validTest, fromSetValid) {
  372. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  373. //reposition & revalidate others
  374. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]), lvp = getLastValidPosition(), i;
  375. for (i = pos; i <= lvp; i++) { //clear selection
  376. delete getMaskSet()["validPositions"][i];
  377. }
  378. getMaskSet()["validPositions"][pos] = validTest;
  379. var valid = true, j;
  380. for (i = pos; i <= lvp ; i++) {
  381. var t = positionsClone[i];
  382. if (t != undefined) {
  383. var vps = getMaskSet()["validPositions"];
  384. if (!opts.keepStatic && vps[i] && (vps[i + 1] != undefined && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || vps[i].alternation != undefined))
  385. j = i + 1;
  386. else
  387. j = seekNext(i);
  388. if (positionCanMatchDefinition(j, t["match"].def)) {
  389. valid = valid && (isValid(j, t["input"], true, true) !== false);
  390. } else valid = t["match"].fn == null;
  391. }
  392. if (!valid) break;
  393. }
  394. if (!valid) {
  395. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  396. return false;
  397. }
  398. } else
  399. getMaskSet()["validPositions"][pos] = validTest;
  400. return true;
  401. }
  402. function stripValidPositions(start, end) {
  403. var i, startPos = start;
  404. if (getMaskSet()["validPositions"][start] != undefined && getMaskSet()["validPositions"][start].input == opts.radixPoint) {
  405. end++;
  406. startPos++;
  407. }
  408. for (i = startPos; i < end; i++) { //clear selection
  409. if (getMaskSet()["validPositions"][i] != undefined &&
  410. (getMaskSet()["validPositions"][i].input != opts.radixPoint || i == getLastValidPosition()))
  411. delete getMaskSet()["validPositions"][i];
  412. }
  413. for (i = end ; i <= getLastValidPosition() ;) {
  414. var t = getMaskSet()["validPositions"][i];
  415. var s = getMaskSet()["validPositions"][startPos];
  416. if (t != undefined && s == undefined) {
  417. if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) {
  418. delete getMaskSet()["validPositions"][i];
  419. i++;
  420. }
  421. startPos++;
  422. } else i++;
  423. }
  424. //remove radixpoint if needed
  425. var lvp = getLastValidPosition();
  426. if (start <= lvp && getMaskSet()["validPositions"][lvp] != undefined && (getMaskSet()["validPositions"][lvp].input == opts.radixPoint))
  427. delete getMaskSet()["validPositions"][lvp];
  428. resetMaskSet(true);
  429. }
  430. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  431. var testPositions = getTests(pos, ndxIntlzr, tstPs),
  432. testPos,
  433. lvp = getLastValidPosition(),
  434. lvTest = getMaskSet()["validPositions"][lvp] || getTests(0)[0],
  435. lvTestAltArr = (lvTest.alternation != undefined) ? lvTest["locator"][lvTest.alternation].split(",") : [];
  436. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  437. testPos = testPositions[ndx];
  438. if (opts.greedy ||
  439. ((testPos["match"] && (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true) &&
  440. (lvTest.alternation == undefined ||
  441. (testPos["locator"][lvTest.alternation] != undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  442. break;
  443. }
  444. }
  445. return testPos;
  446. }
  447. function getTest(pos) {
  448. if (getMaskSet()['validPositions'][pos]) {
  449. return getMaskSet()['validPositions'][pos]["match"];
  450. }
  451. return getTests(pos)[0]["match"];
  452. }
  453. function positionCanMatchDefinition(pos, def) {
  454. var valid = false, tests = getTests(pos);
  455. for (var tndx = 0; tndx < tests.length; tndx++) {
  456. if (tests[tndx]["match"] && tests[tndx]["match"].def == def) {
  457. valid = true;
  458. break;
  459. }
  460. }
  461. return valid;
  462. };
  463. function getTests(pos, ndxIntlzr, tstPs) {
  464. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  465. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  466. function handleMatch(match, loopNdx, quantifierRecurse) {
  467. if (testPos > 10000) {
  468. 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"]);
  469. return true;
  470. }
  471. if (testPos == pos && match.matches == undefined) {
  472. matches.push({ "match": match, "locator": loopNdx.reverse() });
  473. return true;
  474. } else if (match.matches != undefined) {
  475. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  476. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  477. if (match) return true;
  478. } else if (match.isOptional) {
  479. var optionalToken = match;
  480. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  481. if (match) {
  482. var latestMatch = matches[matches.length - 1]["match"];
  483. var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
  484. if (isFirstMatch) {
  485. insertStop = true; //insert a stop for non greedy
  486. }
  487. testPos = pos; //match the position after the group
  488. }
  489. } else if (match.isAlternator) {
  490. var alternateToken = match, malternateMatches = [], maltMatches,
  491. currentMatches = matches.slice(), loopNdxCnt = loopNdx.length;
  492. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  493. if (altIndex == -1 || typeof altIndex == "string") {
  494. var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr;
  495. if (typeof altIndex == "string") altIndexArr = altIndex.split(",");
  496. for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  497. matches = [];
  498. match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  499. maltMatches = matches.slice();
  500. testPos = currentPos;
  501. matches = [];
  502. //cloneback
  503. for (var i = 0; i < ndxInitializerClone.length; i++) {
  504. ndxInitializer[i] = ndxInitializerClone[i];
  505. }
  506. //fuzzy merge matches
  507. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  508. var altMatch = maltMatches[ndx1];
  509. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  510. var altMatch2 = malternateMatches[ndx2];
  511. //verify equality
  512. if (altMatch.match.mask == altMatch2.match.mask && (typeof altIndex != "string" || $.inArray(altMatch.locator[loopNdxCnt].toString(), altIndexArr) != -1)) {
  513. maltMatches.splice(ndx1, 1);
  514. altMatch2.locator[loopNdxCnt] = altMatch2.locator[loopNdxCnt] + "," + altMatch.locator[loopNdxCnt];
  515. altMatch2.alternation = loopNdxCnt; //we pass the alternation index => used in determineLastRequiredPosition
  516. break;
  517. }
  518. }
  519. }
  520. malternateMatches = malternateMatches.concat(maltMatches);
  521. }
  522. if (typeof altIndex == "string") { //filter matches
  523. malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {
  524. if (isFinite(ndx)) {
  525. var altLocArr = lmnt.locator[loopNdxCnt].toString().split(",");
  526. var mamatch;
  527. lmnt.locator[loopNdxCnt] = undefined;
  528. lmnt.alternation = undefined;
  529. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  530. mamatch = $.inArray(altLocArr[alndx], altIndexArr) != -1;
  531. if (mamatch) { //rebuild the locator with valid entries
  532. if (lmnt.locator[loopNdxCnt] != undefined) {
  533. lmnt.locator[loopNdxCnt] += ",";
  534. lmnt.alternation = loopNdxCnt; //only define alternation when there is more then 1 possibility
  535. lmnt.locator[loopNdxCnt] += altLocArr[alndx];
  536. } else
  537. lmnt.locator[loopNdxCnt] = parseInt(altLocArr[alndx]);
  538. }
  539. }
  540. if (lmnt.locator[loopNdxCnt] != undefined) return lmnt;
  541. }
  542. });
  543. }
  544. matches = currentMatches.concat(malternateMatches);
  545. //console.log("alternates " + pos + " -> " + JSON.stringify(matches));
  546. insertStop = true; //insert a stopelemnt when there is an alternate
  547. } else {
  548. match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  549. }
  550. if (match) return true;
  551. } else if (match.isQuantifier && quantifierRecurse !== true) {
  552. var qt = match;
  553. opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!)
  554. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  555. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  556. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  557. if (match) {
  558. //get latest match
  559. var latestMatch = matches[matches.length - 1]["match"];
  560. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  561. var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
  562. if (isFirstMatch) { //search for next possible match
  563. if (qndx > (qt.quantifier.min - 1)) {
  564. insertStop = true;
  565. testPos = pos; //match the position after the group
  566. break; //stop quantifierloop
  567. } else return true;
  568. } else {
  569. return true;
  570. }
  571. }
  572. }
  573. } else {
  574. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  575. if (match)
  576. return true;
  577. }
  578. } else testPos++;
  579. }
  580. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  581. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  582. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  583. if (match && testPos == pos) {
  584. return match;
  585. } else if (testPos > pos) {
  586. break;
  587. }
  588. }
  589. }
  590. }
  591. //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  592. // return getMaskSet()['tests'][pos];
  593. //}
  594. if (ndxIntlzr == undefined) {
  595. var previousPos = pos - 1, test;
  596. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  597. previousPos--;
  598. }
  599. if (test != undefined && previousPos > -1) {
  600. testPos = previousPos;
  601. ndxInitializer = test["locator"].slice();
  602. } else {
  603. previousPos = pos - 1;
  604. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  605. previousPos--;
  606. }
  607. if (test != undefined && previousPos > -1) {
  608. testPos = previousPos;
  609. ndxInitializer = test[0]["locator"].slice();
  610. }
  611. }
  612. }
  613. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  614. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  615. if ((match && testPos == pos) || testPos > pos) {
  616. break;
  617. }
  618. }
  619. if (matches.length == 0 || insertStop)
  620. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  621. getMaskSet()['tests'][pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  622. //console.log(pos + " - " + JSON.stringify(matches));
  623. return getMaskSet()['tests'][pos];
  624. }
  625. function getBufferTemplate() {
  626. if (getMaskSet()['_buffer'] == undefined) {
  627. //generate template
  628. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  629. }
  630. return getMaskSet()['_buffer'];
  631. }
  632. function getBuffer() {
  633. if (getMaskSet()['buffer'] == undefined) {
  634. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  635. }
  636. return getMaskSet()['buffer'];
  637. }
  638. function refreshFromBuffer(start, end, buffer) {
  639. buffer = buffer || getBuffer().slice(); //pass or work on clone
  640. if (start === true) {
  641. resetMaskSet();
  642. start = 0;
  643. end = buffer.length;
  644. } else {
  645. for (var i = start; i < end; i++) {
  646. delete getMaskSet()["validPositions"][i];
  647. delete getMaskSet()["tests"][i];
  648. }
  649. }
  650. for (var i = start; i < end; i++) {
  651. if (buffer[i] != opts.skipOptionalPartCharacter) {
  652. isValid(i, buffer[i], true, true);
  653. }
  654. }
  655. }
  656. function casing(elem, test) {
  657. switch (test.casing) {
  658. case "upper":
  659. elem = elem.toUpperCase();
  660. break;
  661. case "lower":
  662. elem = elem.toLowerCase();
  663. break;
  664. }
  665. return elem;
  666. }
  667. function checkAlternationMatch(altArr1, altArr2) {
  668. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  669. isMatch = false;
  670. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  671. if ($.inArray(altArr1[alndx], altArrC) != -1) {
  672. isMatch = true;
  673. break;
  674. }
  675. }
  676. return isMatch;
  677. }
  678. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  679. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  680. function _isValid(position, c, strict, fromSetValid) {
  681. var rslt = false;
  682. $.each(getTests(position), function (ndx, tst) {
  683. var test = tst["match"];
  684. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  685. for (var i = test.cardinality; i > loopend; i--) {
  686. chrs += getBufferElement(position - (i - 1));
  687. }
  688. if (c) {
  689. chrs += c;
  690. }
  691. //return is false or a json object => { pos: ??, c: ??} or true
  692. rslt = test.fn != null ?
  693. test.fn.test(chrs, getMaskSet(), position, strict, opts)
  694. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  695. { c: test["def"], pos: position }
  696. : false;
  697. if (rslt !== false) {
  698. var elem = rslt.c != undefined ? rslt.c : c;
  699. elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
  700. var validatedPos = position;
  701. if (rslt["remove"] != undefined) { //remove position
  702. stripValidPositions(rslt["remove"], rslt["remove"] + 1);
  703. }
  704. if (rslt["refreshFromBuffer"]) {
  705. var refresh = rslt["refreshFromBuffer"];
  706. strict = true;
  707. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
  708. if (rslt.pos == undefined && rslt.c == undefined) {
  709. rslt.pos = getLastValidPosition();
  710. return false;//breakout if refreshFromBuffer && nothing to insert
  711. }
  712. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  713. if (validatedPos != position) {
  714. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  715. return false;
  716. }
  717. } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
  718. validatedPos = rslt["pos"];
  719. refreshFromBuffer(position, validatedPos);
  720. if (validatedPos != position) {
  721. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  722. return false;
  723. }
  724. }
  725. if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
  726. return false; //breakout if nothing to insert
  727. }
  728. if (ndx > 0) {
  729. resetMaskSet(true);
  730. }
  731. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid))
  732. rslt = false;
  733. return false; //break from $.each
  734. }
  735. });
  736. return rslt;
  737. }
  738. function alternate(pos, c, strict, fromSetValid) {
  739. var validPsClone = $.extend(true, {}, getMaskSet()["validPositions"]),
  740. lastAlt,
  741. alternation;
  742. //find last alternation
  743. for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) {
  744. if (getMaskSet()["validPositions"][lastAlt] && getMaskSet()["validPositions"][lastAlt].alternation != undefined) {
  745. alternation = getMaskSet()["validPositions"][lastAlt].alternation;
  746. break;
  747. }
  748. }
  749. if (alternation != undefined) {
  750. //find first decision making position
  751. for (var decisionPos in getMaskSet()["validPositions"]) {
  752. if (parseInt(decisionPos) > parseInt(lastAlt) && getMaskSet()["validPositions"][decisionPos].alternation === undefined) {
  753. var altPos = getMaskSet()["validPositions"][decisionPos],
  754. decisionTaker = altPos.locator[alternation],
  755. altNdxs = getMaskSet()["validPositions"][lastAlt].locator[alternation].split(",");
  756. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  757. if (decisionTaker < altNdxs[mndx]) {
  758. var possibilityPos, possibilities;
  759. for (var dp = decisionPos - 1; dp >= 0; dp--) {
  760. possibilityPos = getMaskSet()["validPositions"][dp];
  761. if (possibilityPos != undefined) {
  762. possibilities = possibilityPos.locator[alternation]; //store to reset
  763. possibilityPos.locator[alternation] = altNdxs[mndx];
  764. break;
  765. }
  766. }
  767. if (decisionTaker != possibilityPos.locator[alternation]) {
  768. var buffer = getBuffer().slice(); //work on clone
  769. for (var i = decisionPos; i < getLastValidPosition() + 1; i++) {
  770. delete getMaskSet()["validPositions"][i];
  771. delete getMaskSet()["tests"][i];
  772. }
  773. resetMaskSet(true); //clear getbuffer
  774. opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
  775. for (var i = decisionPos; i < buffer.length; i++) {
  776. if (buffer[i] != opts.skipOptionalPartCharacter) {
  777. isValid(getLastValidPosition() + 1, buffer[i], false, true);
  778. }
  779. }
  780. possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete
  781. var isValidRslt = isValid(pos, c, strict, fromSetValid);
  782. opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength
  783. if (!isValidRslt) {
  784. resetMaskSet();
  785. getMaskSet()["validPositions"] = $.extend(true, {}, validPsClone);
  786. } else
  787. return isValidRslt;
  788. }
  789. }
  790. }
  791. break;
  792. }
  793. }
  794. }
  795. return false;
  796. }
  797. //set alternator choice on previous skipped placeholder positions
  798. function trackbackAlternations(originalPos, newPos) {
  799. var vp = getMaskSet()["validPositions"][newPos],
  800. targetLocator = vp.locator,
  801. tll = targetLocator.length;
  802. for (var ps = originalPos; ps < newPos; ps++) {
  803. if (!isMask(ps)) {
  804. var tests = getTests(ps),
  805. bestMatch = tests[0], equality = -1;
  806. $.each(tests, function (ndx, tst) {
  807. for (var i = 0; i < tll; i++) {
  808. if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(','), targetLocator[i].toString().split(',')) && equality < i) {
  809. equality = i;
  810. bestMatch = tst;
  811. }
  812. }
  813. });
  814. setValidPosition(ps, $.extend({}, bestMatch, { "input": bestMatch["match"].def }), true)
  815. }
  816. }
  817. }
  818. //Check for a nonmask before the pos
  819. var buffer = getBuffer();
  820. for (var pndx = pos - 1; pndx > -1; pndx--) {
  821. if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx]["match"].fn == null)
  822. break;
  823. else if (getMaskSet()["validPositions"][pndx] == undefined && (!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) {
  824. _isValid(pndx, buffer[pndx], true);
  825. }
  826. }
  827. var maskPos = pos;
  828. var result = false;
  829. if (fromSetValid && maskPos >= getMaskLength()) {
  830. resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length
  831. }
  832. if (maskPos < getMaskLength()) {
  833. result = _isValid(maskPos, c, strict, fromSetValid);
  834. if (!strict && result === false) {
  835. var currentPosValid = getMaskSet()["validPositions"][maskPos];
  836. if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
  837. result = { "caret": seekNext(maskPos) };
  838. } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
  839. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  840. result = _isValid(nPos, c, strict, fromSetValid);
  841. if (result !== false) {
  842. trackbackAlternations(maskPos, nPos);
  843. maskPos = nPos;
  844. break;
  845. }
  846. }
  847. }
  848. }
  849. }
  850. if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic
  851. result = alternate(pos, c, strict, fromSetValid);
  852. }
  853. if (result === true) result = { "pos": maskPos };
  854. return result;
  855. }
  856. function isMask(pos) {
  857. var test = getTest(pos);
  858. return test.fn != null ? test.fn : false;
  859. }
  860. function getMaskLength() {
  861. var maskLength;
  862. maxLength = $el.prop('maxLength');
  863. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  864. if (opts.greedy == false) {
  865. var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp],
  866. ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
  867. for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
  868. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  869. ndxIntlzr = testPos["locator"].slice();
  870. }
  871. maskLength = pos;
  872. } else
  873. maskLength = getBuffer().length;
  874. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  875. }
  876. function seekNext(pos) {
  877. var maskL = getMaskLength();
  878. if (pos >= maskL) return maskL;
  879. var position = pos;
  880. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
  881. }
  882. return position;
  883. }
  884. function seekPrevious(pos) {
  885. var position = pos;
  886. if (position <= 0) return 0;
  887. while (--position > 0 && !isMask(position)) {
  888. };
  889. return position;
  890. }
  891. function getBufferElement(position) {
  892. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  893. }
  894. function writeBuffer(input, buffer, caretPos) {
  895. input._valueSet(buffer.join(''));
  896. if (caretPos != undefined) {
  897. caret(input, caretPos);
  898. }
  899. }
  900. function getPlaceholder(pos, test) {
  901. test = test || getTest(pos);
  902. return test["placeholder"] != undefined ? test["placeholder"] : (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  903. }
  904. function checkVal(input, writeOut, strict, nptvl) {
  905. var inputValue = nptvl != undefined ? nptvl.slice() : input._valueGet().split('');
  906. resetMaskSet();
  907. if (writeOut) input._valueSet(""); //initial clear
  908. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(''), matches = inputValue.join('').match(new RegExp(escapeRegex(staticInput), "g"));
  909. if (matches && matches.length > 1) {
  910. inputValue.splice(0, staticInput.length);
  911. }
  912. $.each(inputValue, function (ndx, charCode) {
  913. var lvp = getLastValidPosition(), lvTest = getMaskSet()["validPositions"][lvp], nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  914. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, getMaskSet()["p"])) == -1 || strict) {
  915. var pos = strict ? ndx : (nextTest["match"].fn == null ? lvp + 1 : getMaskSet()["p"]);
  916. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, pos);
  917. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  918. } else {
  919. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, true, lvp + 1);
  920. }
  921. });
  922. if (writeOut) {
  923. var keypressResult = opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
  924. handleOnKeyResult(input, keypressResult);
  925. writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined);
  926. }
  927. }
  928. function escapeRegex(str) {
  929. return $.inputmask.escapeRegex.call(this, str);
  930. }
  931. function unmaskedvalue($input) {
  932. if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
  933. var umValue = [], vps = getMaskSet()["validPositions"];
  934. for (var pndx in vps) {
  935. if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
  936. umValue.push(vps[pndx]["input"]);
  937. }
  938. }
  939. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  940. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join('');
  941. if ($.isFunction(opts.onUnMask)) {
  942. unmaskedValue = (opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue);
  943. }
  944. return unmaskedValue;
  945. } else {
  946. return $input[0]._valueGet();
  947. }
  948. }
  949. function TranslatePosition(pos) {
  950. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  951. var bffrLght = getBuffer().length;
  952. pos = bffrLght - pos;
  953. }
  954. return pos;
  955. }
  956. function caret(input, begin, end) {
  957. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  958. if (typeof begin == 'number') {
  959. begin = TranslatePosition(begin);
  960. end = TranslatePosition(end);
  961. end = (typeof end == 'number') ? end : begin;
  962. //store caret for multi scope
  963. var data = $(npt).data('_inputmask') || {};
  964. data["caret"] = { "begin": begin, "end": end };
  965. $(npt).data('_inputmask', data);
  966. if (!$(npt).is(":visible")) {
  967. return;
  968. }
  969. var scrollCalc = $(npt).css("font-size").replace("px", "") * end;
  970. npt.scrollLeft = scrollCalc > npt.scrollWidth ? scrollCalc : 0;
  971. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  972. if (npt.setSelectionRange) {
  973. npt.selectionStart = begin;
  974. npt.selectionEnd = end;
  975. } else if (npt.createTextRange) {
  976. range = npt.createTextRange();
  977. range.collapse(true);
  978. range.moveEnd('character', end);
  979. range.moveStart('character', begin);
  980. range.select();
  981. }
  982. } else {
  983. var data = $(npt).data('_inputmask');
  984. if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
  985. begin = data["caret"]["begin"];
  986. end = data["caret"]["end"];
  987. } else if (npt.setSelectionRange) {
  988. begin = npt.selectionStart;
  989. end = npt.selectionEnd;
  990. } else if (document.selection && document.selection.createRange) {
  991. range = document.selection.createRange();
  992. begin = 0 - range.duplicate().moveStart('character', -100000);
  993. end = begin + range.text.length;
  994. }
  995. begin = TranslatePosition(begin);
  996. end = TranslatePosition(end);
  997. return { "begin": begin, "end": end };
  998. }
  999. }
  1000. function determineLastRequiredPosition(returnDefinition) {
  1001. var buffer = getBuffer(), bl = buffer.length,
  1002. pos, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet()["validPositions"][lvp],
  1003. ndxIntlzr = lvTest != undefined ? lvTest["locator"].slice() : undefined, testPos;
  1004. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1005. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1006. ndxIntlzr = testPos["locator"].slice();
  1007. positions[pos] = $.extend(true, {}, testPos);
  1008. }
  1009. var lvTestAltArr = lvTest && lvTest.alternation != undefined ? lvTest["locator"][lvTest.alternation].split(",") : [];
  1010. for (pos = bl - 1; pos > lvp; pos--) {
  1011. testPos = positions[pos]["match"];
  1012. if ((testPos.optionality ||
  1013. testPos.optionalQuantifier ||
  1014. (lvTest && lvTest.alternation != undefined && positions[pos]["locator"][lvTest.alternation] != undefined && $.inArray(positions[pos]["locator"][lvTest.alternation].toString(), lvTestAltArr) != -1))
  1015. && buffer[pos] == getPlaceholder(pos, testPos)) {
  1016. bl--;
  1017. } else break;
  1018. }
  1019. return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
  1020. }
  1021. function clearOptionalTail(buffer) {
  1022. var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
  1023. for (; lmib > rl; lmib--) {
  1024. if (isMask(lmib)) break;
  1025. }
  1026. buffer.splice(rl, lmib + 1 - rl);
  1027. }
  1028. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1029. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  1030. if (opts.repeat == "*") return undefined;
  1031. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
  1032. if (lvp == aml) {
  1033. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
  1034. complete = true;
  1035. for (var i = 0; i <= aml; i++) {
  1036. var mask = isMask(i);
  1037. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  1038. complete = false;
  1039. break;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. return complete;
  1045. }
  1046. function isSelection(begin, end) {
  1047. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  1048. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  1049. }
  1050. function installEventRuler(npt) {
  1051. var events = $._data(npt).events;
  1052. $.each(events, function (eventType, eventHandlers) {
  1053. $.each(eventHandlers, function (ndx, eventHandler) {
  1054. if (eventHandler.namespace == "inputmask") {
  1055. if (eventHandler.type != "setvalue") {
  1056. var handler = eventHandler.handler;
  1057. eventHandler.handler = function (e) {
  1058. if (this.readOnly || this.disabled)
  1059. e.preventDefault;
  1060. else
  1061. return handler.apply(this, arguments);
  1062. };
  1063. }
  1064. }
  1065. });
  1066. });
  1067. }
  1068. function patchValueProperty(npt) {
  1069. var valueGet;
  1070. var valueSet;
  1071. function PatchValhook(type) {
  1072. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  1073. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  1074. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1075. elem.value = value;
  1076. return elem;
  1077. };
  1078. $.valHooks[type] = {
  1079. get: function (elem) {
  1080. var $elem = $(elem);
  1081. if ($elem.data('_inputmask')) {
  1082. if ($elem.data('_inputmask')['opts'].autoUnmask)
  1083. return $elem.inputmask('unmaskedvalue');
  1084. else {
  1085. var result = valhookGet(elem),
  1086. inputData = $elem.data('_inputmask'),
  1087. maskset = inputData['maskset'],
  1088. bufferTemplate = maskset['_buffer'];
  1089. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  1090. return result != bufferTemplate ? result : '';
  1091. }
  1092. } else return valhookGet(elem);
  1093. },
  1094. set: function (elem, value) {
  1095. var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
  1096. if (inputData) {
  1097. result = valhookSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value);
  1098. $elem.triggerHandler('setvalue.inputmask');
  1099. } else {
  1100. result = valhookSet(elem, value);
  1101. }
  1102. return result;
  1103. },
  1104. inputmaskpatch: true
  1105. };
  1106. }
  1107. }
  1108. function getter() {
  1109. var $self = $(this), inputData = $(this).data('_inputmask');
  1110. if (inputData) {
  1111. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  1112. } else return valueGet.call(this);
  1113. }
  1114. function setter(value) {
  1115. var inputData = $(this).data('_inputmask');
  1116. if (inputData) {
  1117. valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? (inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) || value) : value);
  1118. $(this).triggerHandler('setvalue.inputmask');
  1119. } else {
  1120. valueSet.call(this, value);
  1121. }
  1122. }
  1123. function InstallNativeValueSetFallback(npt) {
  1124. $(npt).bind("mouseenter.inputmask", function (event) {
  1125. var $input = $(this), input = this, value = input._valueGet();
  1126. if (value != "" && value != getBuffer().join('')) {
  1127. valueSet.call(this, $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, value, opts) || value) : value);
  1128. $input.trigger("setvalue");
  1129. }
  1130. });
  1131. //!! the bound handlers are executed in the order they where bound
  1132. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1133. var events = $._data(npt).events;
  1134. var handlers = events["mouseover"];
  1135. if (handlers) {
  1136. var ourHandler = handlers[handlers.length - 1];
  1137. for (var i = handlers.length - 1; i > 0; i--) {
  1138. handlers[i] = handlers[i - 1];
  1139. }
  1140. handlers[0] = ourHandler;
  1141. }
  1142. }
  1143. if (!npt._valueGet) {
  1144. //var valueProperty;
  1145. if (Object.getOwnPropertyDescriptor)
  1146. var valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  1147. if (valueProperty && valueProperty.configurable && false) { //experimental for chrome
  1148. npt._value = valueProperty.value;
  1149. valueGet = function () {
  1150. return this._value || "";
  1151. }
  1152. valueSet = function (value) {
  1153. this._value = value;
  1154. this.select();
  1155. this.setRangeText(value);
  1156. this.selectionStart = this.selectionEnd;
  1157. }
  1158. Object.defineProperty(npt, "value", {
  1159. get: getter,
  1160. set: setter
  1161. });
  1162. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1163. valueGet = npt.__lookupGetter__("value");
  1164. valueSet = npt.__lookupSetter__("value");
  1165. npt.__defineGetter__("value", getter);
  1166. npt.__defineSetter__("value", setter);
  1167. } else { //jquery.val
  1168. valueGet = function () { return npt.value; }
  1169. valueSet = function (value) { npt.value = value; }
  1170. PatchValhook(npt.type);
  1171. InstallNativeValueSetFallback(npt);
  1172. }
  1173. npt._valueGet = function () {
  1174. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  1175. };
  1176. npt._valueSet = function (value) {
  1177. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  1178. };
  1179. }
  1180. }
  1181. function handleRemove(input, k, pos) {
  1182. function generalize() {
  1183. if (opts.keepStatic) {
  1184. resetMaskSet(true);
  1185. var validInputs = [],
  1186. lastAlt;
  1187. //find last alternation
  1188. for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) {
  1189. if (getMaskSet()["validPositions"][lastAlt]) {
  1190. if (getMaskSet()["validPositions"][lastAlt].alternation != undefined) {
  1191. break;
  1192. }
  1193. validInputs.push(getMaskSet()["validPositions"][lastAlt].input);
  1194. delete getMaskSet()["validPositions"][lastAlt];
  1195. }
  1196. }
  1197. if (lastAlt > 0) {
  1198. while (validInputs.length > 0) {
  1199. getMaskSet()["p"] = seekNext(getLastValidPosition());
  1200. keypressEvent.call(input, undefined, true, validInputs.pop().charCodeAt(0), false, false, getMaskSet()["p"]);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. if (opts.numericInput || isRTL) {
  1206. if (k == $.inputmask.keyCode.BACKSPACE)
  1207. k = $.inputmask.keyCode.DELETE;
  1208. else if (k == $.inputmask.keyCode.DELETE)
  1209. k = $.inputmask.keyCode.BACKSPACE;
  1210. if (isRTL) {
  1211. var pend = pos.end;
  1212. pos.end = pos.begin;
  1213. pos.begin = pend;
  1214. }
  1215. }
  1216. if (k == $.inputmask.keyCode.BACKSPACE && pos.end - pos.begin <= 1)
  1217. pos.begin = seekPrevious(pos.begin);
  1218. else if (k == $.inputmask.keyCode.DELETE && pos.begin == pos.end)
  1219. pos.end++;
  1220. stripValidPositions(pos.begin, pos.end);
  1221. generalize(); //revert the alternation
  1222. var firstMaskedPos = getLastValidPosition(pos.begin);
  1223. if (firstMaskedPos < pos.begin) {
  1224. if (firstMaskedPos == -1) resetMaskSet();
  1225. getMaskSet()["p"] = seekNext(firstMaskedPos);
  1226. } else {
  1227. getMaskSet()["p"] = pos.begin;
  1228. }
  1229. }
  1230. //postprocessing of the validpositions according to the buffer manipulations
  1231. function handleOnKeyResult(input, keyResult, caretPos) {
  1232. if (keyResult && keyResult["refreshFromBuffer"]) {
  1233. var refresh = keyResult["refreshFromBuffer"];
  1234. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], keyResult["buffer"]);
  1235. resetMaskSet(true);
  1236. if (caretPos != undefined) {
  1237. writeBuffer(input, getBuffer());
  1238. caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
  1239. }
  1240. }
  1241. }
  1242. function keydownEvent(e) {
  1243. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1244. skipKeyPressEvent = false;
  1245. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1246. //backspace, delete, and escape get special treatment
  1247. if (k == $.inputmask.keyCode.BACKSPACE || k == $.inputmask.keyCode.DELETE || (iphone && k == 127) || (e.ctrlKey && k == 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1248. e.preventDefault(); //stop default action but allow propagation
  1249. if (k == 88) valueOnFocus = getBuffer().join('');
  1250. handleRemove(input, k, pos);
  1251. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  1252. if (input._valueGet() == getBufferTemplate().join(''))
  1253. $input.trigger('cleared');
  1254. if (opts.showTooltip) { //update tooltip
  1255. $input.prop("title", getMaskSet()["mask"]);
  1256. }
  1257. } else if (k == $.inputmask.keyCode.END || k == $.inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1258. setTimeout(function () {
  1259. var caretPos = seekNext(getLastValidPosition());
  1260. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1261. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1262. }, 0);
  1263. } else if ((k == $.inputmask.keyCode.HOME && !e.shiftKey) || k == $.inputmask.keyCode.PAGE_UP) { //Home or page_up
  1264. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1265. } else if (k == $.inputmask.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  1266. checkVal(input, true, false, valueOnFocus.split(''));
  1267. $input.click();
  1268. } else if (k == $.inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1269. opts.insertMode = !opts.insertMode;
  1270. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1271. } else if (opts.insertMode == false && !e.shiftKey) {
  1272. if (k == $.inputmask.keyCode.RIGHT) {
  1273. setTimeout(function () {
  1274. var caretPos = caret(input);
  1275. caret(input, caretPos.begin);
  1276. }, 0);
  1277. } else if (k == $.inputmask.keyCode.LEFT) {
  1278. setTimeout(function () {
  1279. var caretPos = caret(input);
  1280. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1281. }, 0);
  1282. }
  1283. }
  1284. var currentCaretPos = caret(input);
  1285. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), currentCaretPos.begin, opts);
  1286. handleOnKeyResult(input, keydownResult, currentCaretPos);
  1287. ignorable = $.inArray(k, opts.ignorables) != -1;
  1288. }
  1289. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  1290. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1291. if (k == undefined && skipKeyPressEvent) return false;
  1292. skipKeyPressEvent = true;
  1293. var input = this, $input = $(input);
  1294. e = e || window.event;
  1295. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  1296. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1297. return true;
  1298. } else {
  1299. if (k) {
  1300. //special treat the decimal separator
  1301. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1302. var pos = checkval ? { begin: ndx, end: ndx } : caret(input), forwardPosition, c = String.fromCharCode(k);
  1303. //should we clear a possible selection??
  1304. var isSlctn = isSelection(pos.begin, pos.end);
  1305. if (isSlctn) {
  1306. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1307. handleRemove(input, $.inputmask.keyCode.DELETE, pos);
  1308. if (!opts.insertMode) { //preserve some space
  1309. opts.insertMode = !opts.insertMode;
  1310. setValidPosition(pos.begin, strict);
  1311. opts.insertMode = !opts.insertMode;
  1312. }
  1313. isSlctn = !opts.multi;
  1314. }
  1315. getMaskSet()["writeOutBuffer"] = true;
  1316. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1317. var valResult = isValid(p, c, strict);
  1318. if (valResult !== false) {
  1319. if (valResult !== true) {
  1320. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1321. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1322. }
  1323. resetMaskSet(true);
  1324. if (valResult.caret != undefined)
  1325. forwardPosition = valResult.caret;
  1326. else {
  1327. var vps = getMaskSet()["validPositions"];
  1328. if (!opts.keepStatic && (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation != undefined))
  1329. forwardPosition = p + 1;
  1330. else
  1331. forwardPosition = seekNext(p);
  1332. }
  1333. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1334. }
  1335. if (writeOut !== false) {
  1336. var self = this;
  1337. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  1338. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1339. var buffer = getBuffer();
  1340. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1341. if (checkval !== true) {
  1342. setTimeout(function () { //timeout needed for IE
  1343. if (isComplete(buffer) === true)
  1344. $input.trigger("complete");
  1345. skipInputEvent = true;
  1346. $input.trigger("input");
  1347. }, 0);
  1348. }
  1349. } else if (isSlctn) {
  1350. getMaskSet()["buffer"] = undefined;
  1351. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1352. }
  1353. } else if (isSlctn) {
  1354. getMaskSet()["buffer"] = undefined;
  1355. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1356. }
  1357. if (opts.showTooltip) { //update tooltip
  1358. $input.prop("title", getMaskSet()["mask"]);
  1359. }
  1360. if (e) e.preventDefault();
  1361. if (checkval) {
  1362. var keyResult = opts.onKeyPress.call(this, e, getBuffer(), -1, opts);
  1363. if (keyResult) {
  1364. handleOnKeyResult(input, keyResult);
  1365. getMaskSet()["p"] = getLastValidPosition() + 1;
  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);