jquery.inputmask.js 130 KB

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