jquery.inputmask.js 124 KB

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