jquery.inputmask.js 118 KB

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