jquery.inputmask.js 115 KB

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