jquery.inputmask.js 121 KB

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