jquery.inputmask.js 122 KB

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