jquery.inputmask.js 128 KB

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