jquery.inputmask.js 113 KB

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