inputmask.js 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740
  1. /*!
  2. * inputmask.js
  3. * https://github.com/RobinHerbots/Inputmask
  4. * Copyright (c) 2010 - 2018 Robin Herbots
  5. * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. * Version: 4.0.3-beta.1
  7. */
  8. (function(factory) {
  9. if (typeof define === "function" && define.amd) {
  10. define([ "./dependencyLibs/inputmask.dependencyLib", "./global/window" ], factory);
  11. } else if (typeof exports === "object") {
  12. module.exports = factory(require("./dependencyLibs/inputmask.dependencyLib"), require("./global/window"));
  13. } else {
  14. window.Inputmask = factory(window.dependencyLib || jQuery, window);
  15. }
  16. })(function($, window, undefined) {
  17. var document = window.document, ua = navigator.userAgent, ie = ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident/") > 0, mobile = isInputEventSupported("touchstart"), iemobile = /iemobile/i.test(ua), iphone = /iphone/i.test(ua) && !iemobile;
  18. function Inputmask(alias, options, internal) {
  19. if (!(this instanceof Inputmask)) {
  20. return new Inputmask(alias, options, internal);
  21. }
  22. this.el = undefined;
  23. this.events = {};
  24. this.maskset = undefined;
  25. this.refreshValue = false;
  26. if (internal !== true) {
  27. if ($.isPlainObject(alias)) {
  28. options = alias;
  29. } else {
  30. options = options || {};
  31. if (alias) options.alias = alias;
  32. }
  33. this.opts = $.extend(true, {}, this.defaults, options);
  34. this.noMasksCache = options && options.definitions !== undefined;
  35. this.userOptions = options || {};
  36. this.isRTL = this.opts.numericInput;
  37. resolveAlias(this.opts.alias, options, this.opts);
  38. }
  39. }
  40. Inputmask.prototype = {
  41. dataAttribute: "data-inputmask",
  42. defaults: {
  43. placeholder: "_",
  44. optionalmarker: [ "[", "]" ],
  45. quantifiermarker: [ "{", "}" ],
  46. groupmarker: [ "(", ")" ],
  47. alternatormarker: "|",
  48. escapeChar: "\\",
  49. mask: null,
  50. regex: null,
  51. oncomplete: $.noop,
  52. onincomplete: $.noop,
  53. oncleared: $.noop,
  54. repeat: 0,
  55. greedy: false,
  56. autoUnmask: false,
  57. removeMaskOnSubmit: false,
  58. clearMaskOnLostFocus: true,
  59. insertMode: true,
  60. clearIncomplete: false,
  61. alias: null,
  62. onKeyDown: $.noop,
  63. onBeforeMask: null,
  64. onBeforePaste: function(pastedValue, opts) {
  65. return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(this, pastedValue, opts) : pastedValue;
  66. },
  67. onBeforeWrite: null,
  68. onUnMask: null,
  69. showMaskOnFocus: true,
  70. showMaskOnHover: true,
  71. onKeyValidation: $.noop,
  72. skipOptionalPartCharacter: " ",
  73. numericInput: false,
  74. rightAlign: false,
  75. undoOnEscape: true,
  76. radixPoint: "",
  77. _radixDance: false,
  78. groupSeparator: "",
  79. keepStatic: null,
  80. positionCaretOnTab: true,
  81. tabThrough: false,
  82. supportsInputType: [ "text", "tel", "password", "search" ],
  83. 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, 0, 229 ],
  84. isComplete: null,
  85. preValidation: null,
  86. postValidation: null,
  87. staticDefinitionSymbol: undefined,
  88. jitMasking: false,
  89. nullable: true,
  90. inputEventOnly: false,
  91. noValuePatching: false,
  92. positionCaretOnClick: "lvp",
  93. casing: null,
  94. inputmode: "verbatim",
  95. colorMask: false,
  96. disablePredictiveText: false,
  97. importDataAttributes: true
  98. },
  99. definitions: {
  100. 9: {
  101. validator: "[0-9\uff11-\uff19]",
  102. definitionSymbol: "*"
  103. },
  104. a: {
  105. validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
  106. definitionSymbol: "*"
  107. },
  108. "*": {
  109. validator: "[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"
  110. }
  111. },
  112. aliases: {},
  113. masksCache: {},
  114. mask: function(elems) {
  115. var that = this;
  116. function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
  117. if (opts.importDataAttributes === true) {
  118. var attrOptions = npt.getAttribute(dataAttribute), option, dataoptions, optionData, p;
  119. function importOption(option, optionData) {
  120. optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
  121. if (optionData !== null) {
  122. if (typeof optionData === "string") {
  123. if (option.indexOf("on") === 0) optionData = window[optionData]; else if (optionData === "false") optionData = false; else if (optionData === "true") optionData = true;
  124. }
  125. userOptions[option] = optionData;
  126. }
  127. }
  128. if (attrOptions && attrOptions !== "") {
  129. attrOptions = attrOptions.replace(/'/g, '"');
  130. dataoptions = JSON.parse("{" + attrOptions + "}");
  131. }
  132. if (dataoptions) {
  133. optionData = undefined;
  134. for (p in dataoptions) {
  135. if (p.toLowerCase() === "alias") {
  136. optionData = dataoptions[p];
  137. break;
  138. }
  139. }
  140. }
  141. importOption("alias", optionData);
  142. if (userOptions.alias) {
  143. resolveAlias(userOptions.alias, userOptions, opts);
  144. }
  145. for (option in opts) {
  146. if (dataoptions) {
  147. optionData = undefined;
  148. for (p in dataoptions) {
  149. if (p.toLowerCase() === option.toLowerCase()) {
  150. optionData = dataoptions[p];
  151. break;
  152. }
  153. }
  154. }
  155. importOption(option, optionData);
  156. }
  157. }
  158. $.extend(true, opts, userOptions);
  159. if (npt.dir === "rtl" || opts.rightAlign) {
  160. npt.style.textAlign = "right";
  161. }
  162. if (npt.dir === "rtl" || opts.numericInput) {
  163. npt.dir = "ltr";
  164. npt.removeAttribute("dir");
  165. opts.isRTL = true;
  166. }
  167. return Object.keys(userOptions).length;
  168. }
  169. if (typeof elems === "string") {
  170. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  171. }
  172. elems = elems.nodeName ? [ elems ] : elems;
  173. $.each(elems, function(ndx, el) {
  174. var scopedOpts = $.extend(true, {}, that.opts);
  175. if (importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute)) {
  176. var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
  177. if (maskset !== undefined) {
  178. if (el.inputmask !== undefined) {
  179. el.inputmask.opts.autoUnmask = true;
  180. el.inputmask.remove();
  181. }
  182. el.inputmask = new Inputmask(undefined, undefined, true);
  183. el.inputmask.opts = scopedOpts;
  184. el.inputmask.noMasksCache = that.noMasksCache;
  185. el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
  186. el.inputmask.isRTL = scopedOpts.isRTL || scopedOpts.numericInput;
  187. el.inputmask.el = el;
  188. el.inputmask.maskset = maskset;
  189. $.data(el, "_inputmask_opts", scopedOpts);
  190. maskScope.call(el.inputmask, {
  191. action: "mask"
  192. });
  193. }
  194. }
  195. });
  196. return elems && elems[0] ? elems[0].inputmask || this : this;
  197. },
  198. option: function(options, noremask) {
  199. if (typeof options === "string") {
  200. return this.opts[options];
  201. } else if (typeof options === "object") {
  202. $.extend(this.userOptions, options);
  203. if (this.el && noremask !== true) {
  204. this.mask(this.el);
  205. }
  206. return this;
  207. }
  208. },
  209. unmaskedvalue: function(value) {
  210. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  211. return maskScope.call(this, {
  212. action: "unmaskedvalue",
  213. value: value
  214. });
  215. },
  216. remove: function() {
  217. return maskScope.call(this, {
  218. action: "remove"
  219. });
  220. },
  221. getemptymask: function() {
  222. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  223. return maskScope.call(this, {
  224. action: "getemptymask"
  225. });
  226. },
  227. hasMaskedValue: function() {
  228. return !this.opts.autoUnmask;
  229. },
  230. isComplete: function() {
  231. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  232. return maskScope.call(this, {
  233. action: "isComplete"
  234. });
  235. },
  236. getmetadata: function() {
  237. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  238. return maskScope.call(this, {
  239. action: "getmetadata"
  240. });
  241. },
  242. isValid: function(value) {
  243. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  244. return maskScope.call(this, {
  245. action: "isValid",
  246. value: value
  247. });
  248. },
  249. format: function(value, metadata) {
  250. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  251. return maskScope.call(this, {
  252. action: "format",
  253. value: value,
  254. metadata: metadata
  255. });
  256. },
  257. setValue: function(value) {
  258. if (this.el) {
  259. $(this.el).trigger("setvalue", [ value ]);
  260. }
  261. },
  262. analyseMask: function(mask, regexMask, opts) {
  263. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?(?:\|[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g, regexTokenizer = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, escaped = false, currentToken = new MaskToken(), match, m, openenings = [], maskTokens = [], openingToken, currentOpeningToken, alternator, lastMatch, groupToken;
  264. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  265. this.matches = [];
  266. this.openGroup = isGroup || false;
  267. this.alternatorGroup = false;
  268. this.isGroup = isGroup || false;
  269. this.isOptional = isOptional || false;
  270. this.isQuantifier = isQuantifier || false;
  271. this.isAlternator = isAlternator || false;
  272. this.quantifier = {
  273. min: 1,
  274. max: 1
  275. };
  276. }
  277. function insertTestDefinition(mtoken, element, position) {
  278. position = position !== undefined ? position : mtoken.matches.length;
  279. var prevMatch = mtoken.matches[position - 1];
  280. if (regexMask) {
  281. if (element.indexOf("[") === 0 || escaped && /\\d|\\s|\\w]/i.test(element) || element === ".") {
  282. mtoken.matches.splice(position++, 0, {
  283. fn: new RegExp(element, opts.casing ? "i" : ""),
  284. optionality: false,
  285. newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element,
  286. casing: null,
  287. def: element,
  288. placeholder: undefined,
  289. nativeDef: element
  290. });
  291. } else {
  292. if (escaped) element = element[element.length - 1];
  293. $.each(element.split(""), function(ndx, lmnt) {
  294. prevMatch = mtoken.matches[position - 1];
  295. mtoken.matches.splice(position++, 0, {
  296. fn: null,
  297. optionality: false,
  298. newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== lmnt && prevMatch.fn !== null,
  299. casing: null,
  300. def: opts.staticDefinitionSymbol || lmnt,
  301. placeholder: opts.staticDefinitionSymbol !== undefined ? lmnt : undefined,
  302. nativeDef: (escaped ? "'" : "") + lmnt
  303. });
  304. });
  305. }
  306. escaped = false;
  307. } else {
  308. var maskdef = (opts.definitions ? opts.definitions[element] : undefined) || Inputmask.prototype.definitions[element];
  309. if (maskdef && !escaped) {
  310. mtoken.matches.splice(position++, 0, {
  311. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator, opts.casing ? "i" : "") : new function() {
  312. this.test = maskdef.validator;
  313. }() : new RegExp("."),
  314. optionality: false,
  315. newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== (maskdef.definitionSymbol || element),
  316. casing: maskdef.casing,
  317. def: maskdef.definitionSymbol || element,
  318. placeholder: maskdef.placeholder,
  319. nativeDef: element
  320. });
  321. } else {
  322. mtoken.matches.splice(position++, 0, {
  323. fn: null,
  324. optionality: false,
  325. newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element && prevMatch.fn !== null,
  326. casing: null,
  327. def: opts.staticDefinitionSymbol || element,
  328. placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
  329. nativeDef: (escaped ? "'" : "") + element
  330. });
  331. escaped = false;
  332. }
  333. }
  334. }
  335. function verifyGroupMarker(maskToken) {
  336. if (maskToken && maskToken.matches) {
  337. $.each(maskToken.matches, function(ndx, token) {
  338. var nextToken = maskToken.matches[ndx + 1];
  339. if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) {
  340. token.isGroup = false;
  341. if (!regexMask) {
  342. insertTestDefinition(token, opts.groupmarker[0], 0);
  343. if (token.openGroup !== true) {
  344. insertTestDefinition(token, opts.groupmarker[1]);
  345. }
  346. }
  347. }
  348. verifyGroupMarker(token);
  349. });
  350. }
  351. }
  352. function defaultCase() {
  353. if (openenings.length > 0) {
  354. currentOpeningToken = openenings[openenings.length - 1];
  355. insertTestDefinition(currentOpeningToken, m);
  356. if (currentOpeningToken.isAlternator) {
  357. alternator = openenings.pop();
  358. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  359. if (alternator.matches[mndx].isGroup) alternator.matches[mndx].isGroup = false;
  360. }
  361. if (openenings.length > 0) {
  362. currentOpeningToken = openenings[openenings.length - 1];
  363. currentOpeningToken.matches.push(alternator);
  364. } else {
  365. currentToken.matches.push(alternator);
  366. }
  367. }
  368. } else {
  369. insertTestDefinition(currentToken, m);
  370. }
  371. }
  372. function reverseTokens(maskToken) {
  373. function reverseStatic(st) {
  374. if (st === opts.optionalmarker[0]) st = opts.optionalmarker[1]; else if (st === opts.optionalmarker[1]) st = opts.optionalmarker[0]; else if (st === opts.groupmarker[0]) st = opts.groupmarker[1]; else if (st === opts.groupmarker[1]) st = opts.groupmarker[0];
  375. return st;
  376. }
  377. maskToken.matches = maskToken.matches.reverse();
  378. for (var match in maskToken.matches) {
  379. if (maskToken.matches.hasOwnProperty(match)) {
  380. var intMatch = parseInt(match);
  381. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) {
  382. var qt = maskToken.matches[match];
  383. maskToken.matches.splice(match, 1);
  384. maskToken.matches.splice(intMatch + 1, 0, qt);
  385. }
  386. if (maskToken.matches[match].matches !== undefined) {
  387. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  388. } else {
  389. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  390. }
  391. }
  392. }
  393. return maskToken;
  394. }
  395. function groupify(matches) {
  396. var groupToken = new MaskToken(true);
  397. groupToken.openGroup = false;
  398. groupToken.matches = matches;
  399. return groupToken;
  400. }
  401. if (regexMask) {
  402. opts.optionalmarker[0] = undefined;
  403. opts.optionalmarker[1] = undefined;
  404. }
  405. while (match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask)) {
  406. m = match[0];
  407. if (regexMask) {
  408. switch (m.charAt(0)) {
  409. case "?":
  410. m = "{0,1}";
  411. break;
  412. case "+":
  413. case "*":
  414. m = "{" + m + "}";
  415. break;
  416. }
  417. }
  418. if (escaped) {
  419. defaultCase();
  420. continue;
  421. }
  422. switch (m.charAt(0)) {
  423. case "(?=":
  424. break;
  425. case "(?!":
  426. break;
  427. case "(?<=":
  428. break;
  429. case "(?<!":
  430. break;
  431. case opts.escapeChar:
  432. escaped = true;
  433. if (regexMask) {
  434. defaultCase();
  435. }
  436. break;
  437. case opts.optionalmarker[1]:
  438. case opts.groupmarker[1]:
  439. openingToken = openenings.pop();
  440. openingToken.openGroup = false;
  441. if (openingToken !== undefined) {
  442. if (openenings.length > 0) {
  443. currentOpeningToken = openenings[openenings.length - 1];
  444. currentOpeningToken.matches.push(openingToken);
  445. if (currentOpeningToken.isAlternator) {
  446. alternator = openenings.pop();
  447. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  448. alternator.matches[mndx].isGroup = false;
  449. alternator.matches[mndx].alternatorGroup = false;
  450. }
  451. if (openenings.length > 0) {
  452. currentOpeningToken = openenings[openenings.length - 1];
  453. currentOpeningToken.matches.push(alternator);
  454. } else {
  455. currentToken.matches.push(alternator);
  456. }
  457. }
  458. } else {
  459. currentToken.matches.push(openingToken);
  460. }
  461. } else defaultCase();
  462. break;
  463. case opts.optionalmarker[0]:
  464. openenings.push(new MaskToken(false, true));
  465. break;
  466. case opts.groupmarker[0]:
  467. openenings.push(new MaskToken(true));
  468. break;
  469. case opts.quantifiermarker[0]:
  470. var quantifier = new MaskToken(false, false, true);
  471. m = m.replace(/[{}]/g, "");
  472. var mqj = m.split("|"), mq = mqj[0].split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length === 1 ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]);
  473. if (mq0 === "*" || mq0 === "+") {
  474. mq0 = mq1 === "*" ? 0 : 1;
  475. }
  476. quantifier.quantifier = {
  477. min: mq0,
  478. max: mq1,
  479. jit: mqj[1]
  480. };
  481. var matches = openenings.length > 0 ? openenings[openenings.length - 1].matches : currentToken.matches;
  482. match = matches.pop();
  483. if (match.isAlternator) {
  484. matches.push(match);
  485. matches = match.matches;
  486. var groupToken = new MaskToken(true);
  487. var tmpMatch = matches.pop();
  488. matches.push(groupToken);
  489. matches = groupToken.matches;
  490. match = tmpMatch;
  491. }
  492. if (!match.isGroup) {
  493. match = groupify([ match ]);
  494. }
  495. matches.push(match);
  496. matches.push(quantifier);
  497. break;
  498. case opts.alternatormarker:
  499. function groupQuantifier(matches) {
  500. var lastMatch = matches.pop();
  501. if (lastMatch.isQuantifier) {
  502. lastMatch = groupify([ matches.pop(), lastMatch ]);
  503. }
  504. return lastMatch;
  505. }
  506. if (openenings.length > 0) {
  507. currentOpeningToken = openenings[openenings.length - 1];
  508. var subToken = currentOpeningToken.matches[currentOpeningToken.matches.length - 1];
  509. if (currentOpeningToken.openGroup && (subToken.matches === undefined || subToken.isGroup === false && subToken.isAlternator === false)) {
  510. lastMatch = openenings.pop();
  511. } else {
  512. lastMatch = groupQuantifier(currentOpeningToken.matches);
  513. }
  514. } else {
  515. lastMatch = groupQuantifier(currentToken.matches);
  516. }
  517. if (lastMatch.isAlternator) {
  518. openenings.push(lastMatch);
  519. } else {
  520. if (lastMatch.alternatorGroup) {
  521. alternator = openenings.pop();
  522. lastMatch.alternatorGroup = false;
  523. } else {
  524. alternator = new MaskToken(false, false, false, true);
  525. }
  526. alternator.matches.push(lastMatch);
  527. openenings.push(alternator);
  528. if (lastMatch.openGroup) {
  529. lastMatch.openGroup = false;
  530. var alternatorGroup = new MaskToken(true);
  531. alternatorGroup.alternatorGroup = true;
  532. openenings.push(alternatorGroup);
  533. }
  534. }
  535. break;
  536. default:
  537. defaultCase();
  538. }
  539. }
  540. while (openenings.length > 0) {
  541. openingToken = openenings.pop();
  542. currentToken.matches.push(openingToken);
  543. }
  544. if (currentToken.matches.length > 0) {
  545. verifyGroupMarker(currentToken);
  546. maskTokens.push(currentToken);
  547. }
  548. if (opts.numericInput || opts.isRTL) {
  549. reverseTokens(maskTokens[0]);
  550. }
  551. return maskTokens;
  552. }
  553. };
  554. Inputmask.extendDefaults = function(options) {
  555. $.extend(true, Inputmask.prototype.defaults, options);
  556. };
  557. Inputmask.extendDefinitions = function(definition) {
  558. $.extend(true, Inputmask.prototype.definitions, definition);
  559. };
  560. Inputmask.extendAliases = function(alias) {
  561. $.extend(true, Inputmask.prototype.aliases, alias);
  562. };
  563. Inputmask.format = function(value, options, metadata) {
  564. return Inputmask(options).format(value, metadata);
  565. };
  566. Inputmask.unmask = function(value, options) {
  567. return Inputmask(options).unmaskedvalue(value);
  568. };
  569. Inputmask.isValid = function(value, options) {
  570. return Inputmask(options).isValid(value);
  571. };
  572. Inputmask.remove = function(elems) {
  573. if (typeof elems === "string") {
  574. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  575. }
  576. elems = elems.nodeName ? [ elems ] : elems;
  577. $.each(elems, function(ndx, el) {
  578. if (el.inputmask) el.inputmask.remove();
  579. });
  580. };
  581. Inputmask.setValue = function(elems, value) {
  582. if (typeof elems === "string") {
  583. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  584. }
  585. elems = elems.nodeName ? [ elems ] : elems;
  586. $.each(elems, function(ndx, el) {
  587. if (el.inputmask) el.inputmask.setValue(value); else $(el).trigger("setvalue", [ value ]);
  588. });
  589. };
  590. Inputmask.escapeRegex = function(str) {
  591. var specials = [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ];
  592. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  593. };
  594. Inputmask.keyCode = {
  595. BACKSPACE: 8,
  596. BACKSPACE_SAFARI: 127,
  597. DELETE: 46,
  598. DOWN: 40,
  599. END: 35,
  600. ENTER: 13,
  601. ESCAPE: 27,
  602. HOME: 36,
  603. INSERT: 45,
  604. LEFT: 37,
  605. PAGE_DOWN: 34,
  606. PAGE_UP: 33,
  607. RIGHT: 39,
  608. SPACE: 32,
  609. TAB: 9,
  610. UP: 38,
  611. X: 88,
  612. CONTROL: 17
  613. };
  614. Inputmask.dependencyLib = $;
  615. function resolveAlias(aliasStr, options, opts) {
  616. var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
  617. if (aliasDefinition) {
  618. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts);
  619. $.extend(true, opts, aliasDefinition);
  620. $.extend(true, opts, options);
  621. return true;
  622. } else if (opts.mask === null) {
  623. opts.mask = aliasStr;
  624. }
  625. return false;
  626. }
  627. function generateMaskSet(opts, nocache) {
  628. function generateMask(mask, metadata, opts) {
  629. var regexMask = false;
  630. if (mask === null || mask === "") {
  631. regexMask = opts.regex !== null;
  632. if (regexMask) {
  633. mask = opts.regex;
  634. mask = mask.replace(/^(\^)(.*)(\$)$/, "$2");
  635. } else {
  636. regexMask = true;
  637. mask = ".*";
  638. }
  639. }
  640. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  641. opts.placeholder = "";
  642. }
  643. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  644. var repeatStart = opts.repeat === "*" ? 0 : opts.repeat === "+" ? 1 : opts.repeat;
  645. mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
  646. }
  647. var masksetDefinition, maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask;
  648. if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) {
  649. masksetDefinition = {
  650. mask: mask,
  651. maskToken: Inputmask.prototype.analyseMask(mask, regexMask, opts),
  652. validPositions: {},
  653. _buffer: undefined,
  654. buffer: undefined,
  655. tests: {},
  656. excludes: {},
  657. metadata: metadata,
  658. maskLength: undefined
  659. };
  660. if (nocache !== true) {
  661. Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition;
  662. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
  663. }
  664. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
  665. return masksetDefinition;
  666. }
  667. var ms;
  668. if ($.isFunction(opts.mask)) {
  669. opts.mask = opts.mask(opts);
  670. }
  671. if ($.isArray(opts.mask)) {
  672. if (opts.mask.length > 1) {
  673. if (opts.keepStatic === null) {
  674. opts.keepStatic = "auto";
  675. for (var i = 0; i < opts.mask.length; i++) {
  676. if (opts.mask[i].charAt(0) !== opts.mask[0].charAt(0)) {
  677. opts.keepStatic = true;
  678. break;
  679. }
  680. }
  681. }
  682. var altMask = opts.groupmarker[0];
  683. $.each(opts.isRTL ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
  684. if (altMask.length > 1) {
  685. altMask += opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0];
  686. }
  687. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  688. altMask += msk.mask;
  689. } else {
  690. altMask += msk;
  691. }
  692. });
  693. altMask += opts.groupmarker[1];
  694. return generateMask(altMask, opts.mask, opts);
  695. } else opts.mask = opts.mask.pop();
  696. }
  697. if (opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  698. ms = generateMask(opts.mask.mask, opts.mask, opts);
  699. } else {
  700. ms = generateMask(opts.mask, opts.mask, opts);
  701. }
  702. return ms;
  703. }
  704. function isInputEventSupported(eventName) {
  705. var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el;
  706. if (!isSupported) {
  707. el.setAttribute(evName, "return;");
  708. isSupported = typeof el[evName] === "function";
  709. }
  710. el = null;
  711. return isSupported;
  712. }
  713. function maskScope(actionObj, maskset, opts) {
  714. maskset = maskset || this.maskset;
  715. opts = opts || this.opts;
  716. var inputmask = this, el = this.el, isRTL = this.isRTL, undoValue, $el, skipKeyPressEvent = false, skipInputEvent = false, ignorable = false, maxLength, mouseEnter = false, colorMask, originalPlaceholder;
  717. function getMaskTemplate(baseOnInput, minimalPos, includeMode, noJit, clearOptionalTail) {
  718. var greedy = opts.greedy;
  719. if (clearOptionalTail) opts.greedy = false;
  720. minimalPos = minimalPos || 0;
  721. var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos, lvp = getLastValidPosition();
  722. do {
  723. if (baseOnInput === true && getMaskSet().validPositions[pos]) {
  724. testPos = clearOptionalTail && getMaskSet().validPositions[pos].match.optionality === true && getMaskSet().validPositions[pos + 1] === undefined && (getMaskSet().validPositions[pos].generatedInput === true || getMaskSet().validPositions[pos].input == opts.skipOptionalPartCharacter && pos > 0) ? determineTestTemplate(pos, getTests(pos, ndxIntlzr, pos - 1)) : getMaskSet().validPositions[pos];
  725. test = testPos.match;
  726. ndxIntlzr = testPos.locator.slice();
  727. maskTemplate.push(includeMode === true ? testPos.input : includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  728. } else {
  729. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  730. test = testPos.match;
  731. ndxIntlzr = testPos.locator.slice();
  732. var jitMasking = noJit === true ? false : opts.jitMasking !== false ? opts.jitMasking : test.jit;
  733. if (jitMasking === false || jitMasking === undefined || typeof jitMasking === "number" && isFinite(jitMasking) && jitMasking > pos) {
  734. maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  735. }
  736. }
  737. if (opts.keepStatic === "auto") {
  738. if (test.newBlockMarker && test.fn !== null) {
  739. opts.keepStatic = pos - 1;
  740. }
  741. }
  742. pos++;
  743. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || minimalPos > pos);
  744. if (maskTemplate[maskTemplate.length - 1] === "") {
  745. maskTemplate.pop();
  746. }
  747. if (includeMode !== false || getMaskSet().maskLength === undefined) getMaskSet().maskLength = pos - 1;
  748. opts.greedy = greedy;
  749. return maskTemplate;
  750. }
  751. function getMaskSet() {
  752. return maskset;
  753. }
  754. function resetMaskSet(soft) {
  755. var maskset = getMaskSet();
  756. maskset.buffer = undefined;
  757. if (soft !== true) {
  758. maskset.validPositions = {};
  759. maskset.p = 0;
  760. }
  761. }
  762. function getLastValidPosition(closestTo, strict, validPositions) {
  763. var before = -1, after = -1, valids = validPositions || getMaskSet().validPositions;
  764. if (closestTo === undefined) closestTo = -1;
  765. for (var posNdx in valids) {
  766. var psNdx = parseInt(posNdx);
  767. if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
  768. if (psNdx <= closestTo) before = psNdx;
  769. if (psNdx >= closestTo) after = psNdx;
  770. }
  771. }
  772. return before === -1 || before == closestTo ? after : after == -1 ? before : closestTo - before < after - closestTo ? before : after;
  773. }
  774. function getDecisionTaker(tst) {
  775. var decisionTaker = tst.locator[tst.alternation];
  776. if (typeof decisionTaker == "string" && decisionTaker.length > 0) {
  777. decisionTaker = decisionTaker.split(",")[0];
  778. }
  779. return decisionTaker !== undefined ? decisionTaker.toString() : "";
  780. }
  781. function getLocator(tst, align) {
  782. var locator = (tst.alternation != undefined ? tst.mloc[getDecisionTaker(tst)] : tst.locator).join("");
  783. if (locator !== "") while (locator.length < align) locator += "0";
  784. return locator;
  785. }
  786. function determineTestTemplate(pos, tests) {
  787. pos = pos > 0 ? pos - 1 : 0;
  788. var altTest = getTest(pos), targetLocator = getLocator(altTest), tstLocator, closest, bestMatch;
  789. for (var ndx = 0; ndx < tests.length; ndx++) {
  790. var tst = tests[ndx];
  791. tstLocator = getLocator(tst, targetLocator.length);
  792. var distance = Math.abs(tstLocator - targetLocator);
  793. if (closest === undefined || tstLocator !== "" && distance < closest || bestMatch && bestMatch.match.optionality && bestMatch.match.newBlockMarker === "master" && (!tst.match.optionality || !tst.match.newBlockMarker) || bestMatch && bestMatch.match.optionalQuantifier && !tst.match.optionalQuantifier) {
  794. closest = distance;
  795. bestMatch = tst;
  796. }
  797. }
  798. return bestMatch;
  799. }
  800. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  801. return getMaskSet().validPositions[pos] || determineTestTemplate(pos, getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
  802. }
  803. function getTest(pos, tests) {
  804. if (getMaskSet().validPositions[pos]) {
  805. return getMaskSet().validPositions[pos];
  806. }
  807. return (tests || getTests(pos))[0];
  808. }
  809. function positionCanMatchDefinition(pos, def) {
  810. var valid = false, tests = getTests(pos);
  811. for (var tndx = 0; tndx < tests.length; tndx++) {
  812. if (tests[tndx].match && tests[tndx].match.def === def) {
  813. valid = true;
  814. break;
  815. }
  816. }
  817. return valid;
  818. }
  819. function getTests(pos, ndxIntlzr, tstPs) {
  820. var maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [ 0 ], matches = [], insertStop = false, latestMatch, cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "", offset = 0;
  821. function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) {
  822. function handleMatch(match, loopNdx, quantifierRecurse) {
  823. function isFirstMatch(latestMatch, tokenGroup) {
  824. var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  825. if (!firstMatch) {
  826. $.each(tokenGroup.matches, function(ndx, match) {
  827. if (match.isQuantifier === true) firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]); else if (match.hasOwnProperty("matches")) firstMatch = isFirstMatch(latestMatch, match);
  828. if (firstMatch) return false;
  829. });
  830. }
  831. return firstMatch;
  832. }
  833. function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
  834. var bestMatch, indexPos;
  835. if (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) {
  836. $.each(getMaskSet().tests[pos] || [ getMaskSet().validPositions[pos] ], function(ndx, lmnt) {
  837. if (lmnt.mloc[alternateNdx]) {
  838. bestMatch = lmnt;
  839. return false;
  840. }
  841. var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation, ndxPos = lmnt.locator[alternation] !== undefined ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
  842. if ((indexPos === undefined || ndxPos < indexPos) && ndxPos !== -1) {
  843. bestMatch = lmnt;
  844. indexPos = ndxPos;
  845. }
  846. });
  847. }
  848. if (bestMatch) {
  849. var bestMatchAltIndex = bestMatch.locator[bestMatch.alternation];
  850. var locator = bestMatch.mloc[alternateNdx] || bestMatch.mloc[bestMatchAltIndex] || bestMatch.locator;
  851. return locator.slice((targetAlternation !== undefined ? targetAlternation : bestMatch.alternation) + 1);
  852. } else {
  853. return targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
  854. }
  855. }
  856. function isSubsetOf(source, target) {
  857. function expand(pattern) {
  858. var expanded = [], start, end;
  859. for (var i = 0, l = pattern.length; i < l; i++) {
  860. if (pattern.charAt(i) === "-") {
  861. end = pattern.charCodeAt(i + 1);
  862. while (++start < end) expanded.push(String.fromCharCode(start));
  863. } else {
  864. start = pattern.charCodeAt(i);
  865. expanded.push(pattern.charAt(i));
  866. }
  867. }
  868. return expanded.join("");
  869. }
  870. if (opts.regex && source.match.fn !== null && target.match.fn !== null) {
  871. return expand(target.match.def.replace(/[\[\]]/g, "")).indexOf(expand(source.match.def.replace(/[\[\]]/g, ""))) !== -1;
  872. }
  873. return source.match.def === target.match.nativeDef;
  874. }
  875. function staticCanMatchDefinition(source, target) {
  876. var sloc = source.locator.slice(source.alternation).join(""), tloc = target.locator.slice(target.alternation).join(""), canMatch = sloc == tloc, canMatch = canMatch && source.match.fn === null && target.match.fn !== null ? target.match.fn.test(source.match.def, getMaskSet(), pos, false, opts, false) : false;
  877. return canMatch;
  878. }
  879. function setMergeLocators(targetMatch, altMatch) {
  880. if (altMatch === undefined || targetMatch.alternation === altMatch.alternation && targetMatch.locator[targetMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
  881. targetMatch.mloc = targetMatch.mloc || {};
  882. var locNdx = targetMatch.locator[targetMatch.alternation];
  883. if (locNdx === undefined) targetMatch.alternation = undefined; else {
  884. if (typeof locNdx === "string") locNdx = locNdx.split(",")[0];
  885. if (targetMatch.mloc[locNdx] === undefined) targetMatch.mloc[locNdx] = targetMatch.locator.slice();
  886. if (altMatch !== undefined) {
  887. for (var ndx in altMatch.mloc) {
  888. if (typeof ndx === "string") ndx = ndx.split(",")[0];
  889. if (targetMatch.mloc[ndx] === undefined) targetMatch.mloc[ndx] = altMatch.mloc[ndx];
  890. }
  891. targetMatch.locator[targetMatch.alternation] = Object.keys(targetMatch.mloc).join(",");
  892. }
  893. return true;
  894. }
  895. }
  896. return false;
  897. }
  898. if (testPos > 500 && quantifierRecurse !== undefined) {
  899. throw "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;
  900. }
  901. if (testPos === pos && match.matches === undefined) {
  902. matches.push({
  903. match: match,
  904. locator: loopNdx.reverse(),
  905. cd: cacheDependency,
  906. mloc: {}
  907. });
  908. return true;
  909. } else if (match.matches !== undefined) {
  910. if (match.isGroup && quantifierRecurse !== match) {
  911. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx, quantifierRecurse);
  912. if (match) return true;
  913. } else if (match.isOptional) {
  914. var optionalToken = match;
  915. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  916. if (match) {
  917. $.each(matches, function(ndx, mtch) {
  918. mtch.match.optionality = true;
  919. });
  920. latestMatch = matches[matches.length - 1].match;
  921. if (quantifierRecurse === undefined && isFirstMatch(latestMatch, optionalToken)) {
  922. insertStop = true;
  923. testPos = pos;
  924. } else return true;
  925. }
  926. } else if (match.isAlternator) {
  927. var alternateToken = match, malternateMatches = [], maltMatches, currentMatches = matches.slice(), loopNdxCnt = loopNdx.length;
  928. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  929. if (altIndex === -1 || typeof altIndex === "string") {
  930. var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr = [], amndx;
  931. if (typeof altIndex == "string") {
  932. altIndexArr = altIndex.split(",");
  933. } else {
  934. for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  935. altIndexArr.push(amndx.toString());
  936. }
  937. }
  938. if (getMaskSet().excludes[pos]) {
  939. var altIndexArrClone = altIndexArr.slice();
  940. for (var i = 0, el = getMaskSet().excludes[pos].length; i < el; i++) {
  941. altIndexArr.splice(altIndexArr.indexOf(getMaskSet().excludes[pos][i].toString()), 1);
  942. }
  943. if (altIndexArr.length === 0) {
  944. getMaskSet().excludes[pos] = undefined;
  945. altIndexArr = altIndexArrClone;
  946. }
  947. }
  948. if (opts.keepStatic === true || isFinite(parseInt(opts.keepStatic)) && currentPos >= opts.keepStatic) altIndexArr = altIndexArr.slice(0, 1);
  949. var unMatchedAlternation = false;
  950. for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
  951. amndx = parseInt(altIndexArr[ndx]);
  952. matches = [];
  953. ndxInitializer = typeof altIndex === "string" ? resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice() : ndxInitializerClone.slice();
  954. if (alternateToken.matches[amndx] && handleMatch(alternateToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse)) match = true; else if (ndx === 0) {
  955. unMatchedAlternation = true;
  956. }
  957. maltMatches = matches.slice();
  958. testPos = currentPos;
  959. matches = [];
  960. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  961. var altMatch = maltMatches[ndx1], dropMatch = false;
  962. altMatch.match.jit = altMatch.match.jit || unMatchedAlternation;
  963. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  964. setMergeLocators(altMatch);
  965. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  966. var altMatch2 = malternateMatches[ndx2];
  967. if (typeof altIndex !== "string" || altMatch.alternation !== undefined && $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
  968. if (altMatch.match.nativeDef === altMatch2.match.nativeDef) {
  969. dropMatch = true;
  970. setMergeLocators(altMatch2, altMatch);
  971. break;
  972. } else if (isSubsetOf(altMatch, altMatch2)) {
  973. if (setMergeLocators(altMatch, altMatch2)) {
  974. dropMatch = true;
  975. malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
  976. }
  977. break;
  978. } else if (isSubsetOf(altMatch2, altMatch)) {
  979. setMergeLocators(altMatch2, altMatch);
  980. break;
  981. } else if (staticCanMatchDefinition(altMatch, altMatch2)) {
  982. if (setMergeLocators(altMatch, altMatch2)) {
  983. dropMatch = true;
  984. malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
  985. }
  986. break;
  987. }
  988. }
  989. }
  990. if (!dropMatch) {
  991. malternateMatches.push(altMatch);
  992. }
  993. }
  994. }
  995. matches = currentMatches.concat(malternateMatches);
  996. testPos = pos;
  997. insertStop = matches.length > 0;
  998. match = malternateMatches.length > 0;
  999. ndxInitializer = ndxInitializerClone.slice();
  1000. } else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse);
  1001. if (match) return true;
  1002. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  1003. var qt = match;
  1004. for (var qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && testPos <= pos; qndx++) {
  1005. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  1006. match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), tokenGroup);
  1007. if (match) {
  1008. latestMatch = matches[matches.length - 1].match;
  1009. latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1;
  1010. latestMatch.jit = (qndx || 1) * tokenGroup.matches.indexOf(latestMatch) >= qt.quantifier.jit;
  1011. if (latestMatch.optionalQuantifier && isFirstMatch(latestMatch, tokenGroup)) {
  1012. insertStop = true;
  1013. testPos = pos;
  1014. break;
  1015. }
  1016. if (latestMatch.jit && !latestMatch.optionalQuantifier) {
  1017. offset = tokenGroup.matches.indexOf(latestMatch);
  1018. testPos = pos;
  1019. insertStop = true;
  1020. break;
  1021. }
  1022. return true;
  1023. }
  1024. }
  1025. } else {
  1026. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  1027. if (match) return true;
  1028. }
  1029. } else {
  1030. testPos++;
  1031. }
  1032. }
  1033. for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx = tndx + 1 + offset) {
  1034. offset = 0;
  1035. if (maskToken.matches[tndx].isQuantifier !== true) {
  1036. var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse);
  1037. if (match && testPos === pos) {
  1038. return match;
  1039. } else if (testPos > pos) {
  1040. break;
  1041. }
  1042. }
  1043. }
  1044. }
  1045. function mergeLocators(pos, tests) {
  1046. var locator = [];
  1047. if (!$.isArray(tests)) tests = [ tests ];
  1048. if (tests.length > 0) {
  1049. if (tests[0].alternation === undefined) {
  1050. locator = determineTestTemplate(pos, tests.slice()).locator.slice();
  1051. if (locator.length === 0) locator = tests[0].locator.slice();
  1052. } else {
  1053. $.each(tests, function(ndx, tst) {
  1054. if (tst.def !== "") {
  1055. if (locator.length === 0) locator = tst.locator.slice(); else {
  1056. for (var i = 0; i < locator.length; i++) {
  1057. if (tst.locator[i] && locator[i].toString().indexOf(tst.locator[i]) === -1) {
  1058. locator[i] += "," + tst.locator[i];
  1059. }
  1060. }
  1061. }
  1062. }
  1063. });
  1064. }
  1065. }
  1066. return locator;
  1067. }
  1068. if (pos > -1) {
  1069. if (ndxIntlzr === undefined) {
  1070. var previousPos = pos - 1, test;
  1071. while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
  1072. previousPos--;
  1073. }
  1074. if (test !== undefined && previousPos > -1) {
  1075. ndxInitializer = mergeLocators(previousPos, test);
  1076. cacheDependency = ndxInitializer.join("");
  1077. testPos = previousPos;
  1078. }
  1079. }
  1080. if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) {
  1081. return getMaskSet().tests[pos];
  1082. }
  1083. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1084. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]);
  1085. if (match && testPos === pos || testPos > pos) {
  1086. break;
  1087. }
  1088. }
  1089. }
  1090. if (matches.length === 0 || insertStop) {
  1091. matches.push({
  1092. match: {
  1093. fn: null,
  1094. optionality: false,
  1095. casing: null,
  1096. def: "",
  1097. placeholder: ""
  1098. },
  1099. locator: [],
  1100. mloc: {},
  1101. cd: cacheDependency
  1102. });
  1103. }
  1104. if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) {
  1105. return $.extend(true, [], matches);
  1106. }
  1107. getMaskSet().tests[pos] = $.extend(true, [], matches);
  1108. return getMaskSet().tests[pos];
  1109. }
  1110. function getBufferTemplate() {
  1111. if (getMaskSet()._buffer === undefined) {
  1112. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1113. if (getMaskSet().buffer === undefined) getMaskSet().buffer = getMaskSet()._buffer.slice();
  1114. }
  1115. return getMaskSet()._buffer;
  1116. }
  1117. function getBuffer(noCache) {
  1118. if (getMaskSet().buffer === undefined || noCache === true) {
  1119. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1120. }
  1121. return getMaskSet().buffer;
  1122. }
  1123. function refreshFromBuffer(start, end, buffer) {
  1124. var i, p;
  1125. if (start === true) {
  1126. resetMaskSet();
  1127. start = 0;
  1128. end = buffer.length;
  1129. } else {
  1130. for (i = start; i < end; i++) {
  1131. delete getMaskSet().validPositions[i];
  1132. }
  1133. }
  1134. p = start;
  1135. for (i = start; i < end; i++) {
  1136. resetMaskSet(true);
  1137. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1138. var valResult = isValid(p, buffer[i], true, true);
  1139. if (valResult !== false) {
  1140. resetMaskSet(true);
  1141. p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. function casing(elem, test, pos) {
  1147. switch (opts.casing || test.casing) {
  1148. case "upper":
  1149. elem = elem.toUpperCase();
  1150. break;
  1151. case "lower":
  1152. elem = elem.toLowerCase();
  1153. break;
  1154. case "title":
  1155. var posBefore = getMaskSet().validPositions[pos - 1];
  1156. if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
  1157. elem = elem.toUpperCase();
  1158. } else {
  1159. elem = elem.toLowerCase();
  1160. }
  1161. break;
  1162. default:
  1163. if ($.isFunction(opts.casing)) {
  1164. var args = Array.prototype.slice.call(arguments);
  1165. args.push(getMaskSet().validPositions);
  1166. elem = opts.casing.apply(this, args);
  1167. }
  1168. }
  1169. return elem;
  1170. }
  1171. function checkAlternationMatch(altArr1, altArr2, na) {
  1172. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = false, naArr = na !== undefined ? na.split(",") : [], naNdx;
  1173. for (var i = 0; i < naArr.length; i++) {
  1174. if ((naNdx = altArr1.indexOf(naArr[i])) !== -1) {
  1175. altArr1.splice(naNdx, 1);
  1176. }
  1177. }
  1178. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1179. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1180. isMatch = true;
  1181. break;
  1182. }
  1183. }
  1184. return isMatch;
  1185. }
  1186. function alternate(pos, c, strict, fromSetValid, rAltPos) {
  1187. var validPsClone = $.extend(true, {}, getMaskSet().validPositions), lastAlt, alternation, isValidRslt = false, altPos, prevAltPos, i, validPos, decisionPos, lAltPos = rAltPos !== undefined ? rAltPos : getLastValidPosition();
  1188. if (lAltPos === -1 && rAltPos === undefined) {
  1189. lastAlt = 0;
  1190. prevAltPos = getTest(lastAlt);
  1191. alternation = prevAltPos.alternation;
  1192. } else {
  1193. for (;lAltPos >= 0; lAltPos--) {
  1194. altPos = getMaskSet().validPositions[lAltPos];
  1195. if (altPos && altPos.alternation !== undefined) {
  1196. if (prevAltPos && prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1197. break;
  1198. }
  1199. lastAlt = lAltPos;
  1200. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1201. prevAltPos = altPos;
  1202. }
  1203. }
  1204. }
  1205. if (alternation !== undefined) {
  1206. decisionPos = parseInt(lastAlt);
  1207. getMaskSet().excludes[decisionPos] = getMaskSet().excludes[decisionPos] || [];
  1208. if (pos !== true) {
  1209. getMaskSet().excludes[decisionPos].push(getDecisionTaker(prevAltPos));
  1210. }
  1211. var validInputsClone = [], staticInputsBeforePos = 0;
  1212. for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) {
  1213. validPos = getMaskSet().validPositions[i];
  1214. if (validPos && validPos.generatedInput !== true) {
  1215. validInputsClone.push(validPos.input);
  1216. } else if (i < pos) staticInputsBeforePos++;
  1217. delete getMaskSet().validPositions[i];
  1218. }
  1219. while (getMaskSet().excludes[decisionPos] && getMaskSet().excludes[decisionPos].length < 10) {
  1220. var posOffset = staticInputsBeforePos * -1, validInputs = validInputsClone.slice();
  1221. getMaskSet().tests[decisionPos] = undefined;
  1222. resetMaskSet(true);
  1223. isValidRslt = true;
  1224. while (validInputs.length > 0) {
  1225. var input = validInputs.shift();
  1226. if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
  1227. break;
  1228. }
  1229. }
  1230. if (isValidRslt && c !== undefined) {
  1231. var targetLvp = getLastValidPosition(pos) + 1;
  1232. for (i = decisionPos; i < getLastValidPosition() + 1; i++) {
  1233. validPos = getMaskSet().validPositions[i];
  1234. if ((validPos === undefined || validPos.match.fn == null) && i < pos + posOffset) {
  1235. posOffset++;
  1236. }
  1237. }
  1238. pos = pos + posOffset;
  1239. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
  1240. }
  1241. if (!isValidRslt) {
  1242. resetMaskSet();
  1243. prevAltPos = getTest(decisionPos);
  1244. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1245. if (getMaskSet().excludes[decisionPos]) {
  1246. var decisionTaker = getDecisionTaker(prevAltPos);
  1247. if (getMaskSet().excludes[decisionPos].indexOf(decisionTaker) !== -1) {
  1248. isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
  1249. break;
  1250. }
  1251. getMaskSet().excludes[decisionPos].push(decisionTaker);
  1252. for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) delete getMaskSet().validPositions[i];
  1253. } else {
  1254. isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
  1255. break;
  1256. }
  1257. } else break;
  1258. }
  1259. }
  1260. getMaskSet().excludes[decisionPos] = undefined;
  1261. return isValidRslt;
  1262. }
  1263. function isValid(pos, c, strict, fromSetValid, fromAlternate, validateOnly) {
  1264. function isSelection(posObj) {
  1265. return isRTL ? posObj.begin - posObj.end > 1 || posObj.begin - posObj.end === 1 : posObj.end - posObj.begin > 1 || posObj.end - posObj.begin === 1;
  1266. }
  1267. strict = strict === true;
  1268. var maskPos = pos;
  1269. if (pos.begin !== undefined) {
  1270. maskPos = isRTL ? pos.end : pos.begin;
  1271. }
  1272. function _isValid(position, c, strict) {
  1273. var rslt = false;
  1274. $.each(getTests(position), function(ndx, tst) {
  1275. var test = tst.match;
  1276. getBuffer(true);
  1277. rslt = test.fn != null ? test.fn.test(c, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? {
  1278. c: getPlaceholder(position, test, true) || test.def,
  1279. pos: position
  1280. } : false;
  1281. if (rslt !== false) {
  1282. var elem = rslt.c !== undefined ? rslt.c : c, validatedPos = position;
  1283. elem = elem === opts.skipOptionalPartCharacter && test.fn === null ? getPlaceholder(position, test, true) || test.def : elem;
  1284. if (rslt.remove !== undefined) {
  1285. if (!$.isArray(rslt.remove)) rslt.remove = [ rslt.remove ];
  1286. $.each(rslt.remove.sort(function(a, b) {
  1287. return b - a;
  1288. }), function(ndx, lmnt) {
  1289. revalidateMask({
  1290. begin: lmnt,
  1291. end: lmnt + 1
  1292. });
  1293. });
  1294. }
  1295. if (rslt.insert !== undefined) {
  1296. if (!$.isArray(rslt.insert)) rslt.insert = [ rslt.insert ];
  1297. $.each(rslt.insert.sort(function(a, b) {
  1298. return a - b;
  1299. }), function(ndx, lmnt) {
  1300. isValid(lmnt.pos, lmnt.c, true, fromSetValid);
  1301. });
  1302. }
  1303. if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) {
  1304. validatedPos = rslt.pos;
  1305. }
  1306. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1307. return false;
  1308. }
  1309. if (!revalidateMask(pos, $.extend({}, tst, {
  1310. input: casing(elem, test, validatedPos)
  1311. }), fromSetValid, validatedPos)) {
  1312. rslt = false;
  1313. }
  1314. return false;
  1315. }
  1316. });
  1317. return rslt;
  1318. }
  1319. var result = true, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
  1320. if ($.isFunction(opts.preValidation) && !strict && fromSetValid !== true && validateOnly !== true) {
  1321. result = opts.preValidation(getBuffer(), maskPos, c, isSelection(pos), opts, getMaskSet());
  1322. }
  1323. if (result === true) {
  1324. trackbackPositions(undefined, maskPos, true);
  1325. if (maxLength === undefined || maskPos < maxLength) {
  1326. result = _isValid(maskPos, c, strict);
  1327. if ((!strict || fromSetValid === true) && result === false && validateOnly !== true) {
  1328. var currentPosValid = getMaskSet().validPositions[maskPos];
  1329. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1330. result = {
  1331. caret: seekNext(maskPos)
  1332. };
  1333. } else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos, true)) {
  1334. for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1335. result = _isValid(nPos, c, strict);
  1336. if (result !== false) {
  1337. result = trackbackPositions(maskPos, result.pos !== undefined ? result.pos : nPos) || result;
  1338. maskPos = nPos;
  1339. break;
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. if (result === false && opts.keepStatic !== false && (opts.regex == null || isComplete(getBuffer())) && !strict && fromAlternate !== true) {
  1346. result = alternate(maskPos, c, strict, fromSetValid);
  1347. }
  1348. if (result === true) {
  1349. result = {
  1350. pos: maskPos
  1351. };
  1352. }
  1353. }
  1354. if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true && validateOnly !== true) {
  1355. var postResult = opts.postValidation(getBuffer(true), pos.begin !== undefined ? isRTL ? pos.end : pos.begin : pos, result, opts);
  1356. if (postResult !== undefined) {
  1357. if (postResult.refreshFromBuffer && postResult.buffer) {
  1358. var refresh = postResult.refreshFromBuffer;
  1359. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postResult.buffer);
  1360. }
  1361. result = postResult === true ? result : postResult;
  1362. }
  1363. }
  1364. if (result && result.pos === undefined) {
  1365. result.pos = maskPos;
  1366. }
  1367. if (result === false || validateOnly === true) {
  1368. resetMaskSet(true);
  1369. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1370. }
  1371. return result;
  1372. }
  1373. function trackbackPositions(originalPos, newPos, fillOnly) {
  1374. var result;
  1375. if (originalPos === undefined) {
  1376. for (originalPos = newPos - 1; originalPos > 0; originalPos--) {
  1377. if (getMaskSet().validPositions[originalPos]) break;
  1378. }
  1379. }
  1380. for (var ps = originalPos; ps < newPos; ps++) {
  1381. if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
  1382. var vp = ps == 0 ? getTest(ps) : getMaskSet().validPositions[ps - 1];
  1383. if (vp) {
  1384. var tests = getTests(ps).slice();
  1385. if (tests[tests.length - 1].match.def === "") tests.pop();
  1386. var bestMatch = determineTestTemplate(ps, tests);
  1387. bestMatch = $.extend({}, bestMatch, {
  1388. input: getPlaceholder(ps, bestMatch.match, true) || bestMatch.match.def
  1389. });
  1390. bestMatch.generatedInput = true;
  1391. revalidateMask(ps, bestMatch, true);
  1392. if (fillOnly !== true) {
  1393. var cvpInput = getMaskSet().validPositions[newPos].input;
  1394. getMaskSet().validPositions[newPos] = undefined;
  1395. result = isValid(newPos, cvpInput, true, true);
  1396. }
  1397. }
  1398. }
  1399. }
  1400. return result;
  1401. }
  1402. function revalidateMask(pos, validTest, fromSetValid, validatedPos) {
  1403. function IsEnclosedStatic(pos, valids, selection) {
  1404. var posMatch = valids[pos];
  1405. if (posMatch !== undefined && (posMatch.match.fn === null && posMatch.match.optionality !== true || posMatch.input === opts.radixPoint)) {
  1406. var prevMatch = selection.begin <= pos - 1 ? valids[pos - 1] && valids[pos - 1].match.fn === null && valids[pos - 1] : valids[pos - 1], nextMatch = selection.end > pos + 1 ? valids[pos + 1] && valids[pos + 1].match.fn === null && valids[pos + 1] : valids[pos + 1];
  1407. return prevMatch && nextMatch;
  1408. }
  1409. return false;
  1410. }
  1411. var begin = pos.begin !== undefined ? pos.begin : pos, end = pos.end !== undefined ? pos.end : pos;
  1412. if (pos.begin > pos.end) {
  1413. begin = pos.end;
  1414. end = pos.begin;
  1415. }
  1416. validatedPos = validatedPos !== undefined ? validatedPos : begin;
  1417. if (begin !== end || opts.insertMode && getMaskSet().validPositions[validatedPos] !== undefined && fromSetValid === undefined) {
  1418. var positionsClone = $.extend(true, {}, getMaskSet().validPositions), lvp = getLastValidPosition(undefined, true), i;
  1419. getMaskSet().p = begin;
  1420. for (i = lvp; i >= begin; i--) {
  1421. if (getMaskSet().validPositions[i] && getMaskSet().validPositions[i].match.nativeDef === "+") {
  1422. opts.isNegative = false;
  1423. }
  1424. delete getMaskSet().validPositions[i];
  1425. }
  1426. var valid = true, j = validatedPos, vps = getMaskSet().validPositions, needsValidation = false, posMatch = j, i = j;
  1427. if (validTest) {
  1428. getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
  1429. posMatch++;
  1430. j++;
  1431. if (begin < end) i++;
  1432. }
  1433. for (;i <= lvp; i++) {
  1434. var t = positionsClone[i];
  1435. if (t !== undefined && (i >= end || i >= begin && t.generatedInput !== true && IsEnclosedStatic(i, positionsClone, {
  1436. begin: begin,
  1437. end: end
  1438. }))) {
  1439. while (getTest(posMatch).match.def !== "") {
  1440. if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.nativeDef === t.match.nativeDef) {
  1441. getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
  1442. getMaskSet().validPositions[posMatch].input = t.input;
  1443. trackbackPositions(undefined, posMatch, true);
  1444. j = posMatch + 1;
  1445. valid = true;
  1446. } else if (positionCanMatchDefinition(posMatch, t.match.def)) {
  1447. var result = isValid(posMatch, t.input, true, true);
  1448. valid = result !== false;
  1449. j = result.caret || result.insert ? getLastValidPosition() : posMatch + 1;
  1450. needsValidation = true;
  1451. } else {
  1452. valid = t.generatedInput === true || t.input === opts.radixPoint && opts.numericInput === true;
  1453. }
  1454. if (valid) break;
  1455. if (!valid && posMatch > end && isMask(posMatch, true) && (t.match.fn !== null || posMatch > getMaskSet().maskLength)) {
  1456. break;
  1457. }
  1458. posMatch++;
  1459. }
  1460. if (getTest(posMatch).match.def == "") valid = false;
  1461. posMatch = j;
  1462. }
  1463. if (!valid) break;
  1464. }
  1465. if (!valid) {
  1466. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1467. resetMaskSet(true);
  1468. return false;
  1469. }
  1470. } else if (validTest) {
  1471. getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
  1472. }
  1473. resetMaskSet(true);
  1474. return true;
  1475. }
  1476. function isMask(pos, strict) {
  1477. var test = getTestTemplate(pos).match;
  1478. if (test.def === "") test = getTest(pos).match;
  1479. if (test.fn != null) {
  1480. return test.fn;
  1481. }
  1482. if (strict !== true && pos > -1) {
  1483. var tests = getTests(pos);
  1484. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1485. }
  1486. return false;
  1487. }
  1488. function seekNext(pos, newBlock) {
  1489. var position = pos + 1;
  1490. while (getTest(position).match.def !== "" && (newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position)) || newBlock !== true && !isMask(position))) {
  1491. position++;
  1492. }
  1493. return position;
  1494. }
  1495. function seekPrevious(pos, newBlock) {
  1496. var position = pos, tests;
  1497. if (position <= 0) return 0;
  1498. while (--position > 0 && (newBlock === true && getTest(position).match.newBlockMarker !== true || newBlock !== true && !isMask(position) && (tests = getTests(position),
  1499. tests.length < 2 || tests.length === 2 && tests[1].match.def === ""))) {}
  1500. return position;
  1501. }
  1502. function getBufferElement(position) {
  1503. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1504. }
  1505. function writeBuffer(input, buffer, caretPos, event, triggerEvents) {
  1506. if (event && $.isFunction(opts.onBeforeWrite)) {
  1507. var result = opts.onBeforeWrite.call(inputmask, event, buffer, caretPos, opts);
  1508. if (result) {
  1509. if (result.refreshFromBuffer) {
  1510. var refresh = result.refreshFromBuffer;
  1511. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1512. buffer = getBuffer(true);
  1513. }
  1514. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1515. }
  1516. }
  1517. if (input !== undefined) {
  1518. input.inputmask._valueSet(buffer.join(""));
  1519. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1520. caret(input, caretPos);
  1521. } else renderColorMask(input, caretPos, buffer.length === 0);
  1522. if (triggerEvents === true) {
  1523. var $input = $(input), nptVal = input.inputmask._valueGet();
  1524. skipInputEvent = true;
  1525. $input.trigger("input");
  1526. setTimeout(function() {
  1527. if (nptVal === getBufferTemplate().join("")) {
  1528. $input.trigger("cleared");
  1529. } else if (isComplete(buffer) === true) {
  1530. $input.trigger("complete");
  1531. }
  1532. }, 0);
  1533. }
  1534. }
  1535. }
  1536. function getPlaceholder(pos, test, returnPL) {
  1537. test = test || getTest(pos).match;
  1538. if (test.placeholder !== undefined || returnPL === true) {
  1539. return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
  1540. } else if (test.fn === null) {
  1541. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1542. var tests = getTests(pos), staticAlternations = [], prevTest;
  1543. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1544. for (var i = 0; i < tests.length; i++) {
  1545. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true && (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1546. staticAlternations.push(tests[i]);
  1547. if (tests[i].match.fn === null) prevTest = tests[i];
  1548. if (staticAlternations.length > 1) {
  1549. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1550. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. }
  1556. }
  1557. return test.def;
  1558. }
  1559. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1560. }
  1561. function HandleNativePlaceholder(npt, value) {
  1562. if (ie && npt.inputmask._valueGet() !== value) {
  1563. var buffer = getBuffer().slice(), nptValue = npt.inputmask._valueGet();
  1564. if (nptValue !== value) {
  1565. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  1566. buffer = [];
  1567. } else {
  1568. clearOptionalTail(buffer);
  1569. }
  1570. writeBuffer(npt, buffer);
  1571. }
  1572. } else if (npt.placeholder !== value) {
  1573. npt.placeholder = value;
  1574. if (npt.placeholder === "") npt.removeAttribute("placeholder");
  1575. }
  1576. }
  1577. var EventRuler = {
  1578. on: function(input, eventName, eventHandler) {
  1579. var ev = function(e) {
  1580. var that = this;
  1581. if (that.inputmask === undefined && this.nodeName !== "FORM") {
  1582. var imOpts = $.data(that, "_inputmask_opts");
  1583. if (imOpts) new Inputmask(imOpts).mask(that); else EventRuler.off(that);
  1584. } else if (e.type !== "setvalue" && this.nodeName !== "FORM" && (that.disabled || that.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || opts.tabThrough === false && e.keyCode === Inputmask.keyCode.TAB))) {
  1585. e.preventDefault();
  1586. } else {
  1587. switch (e.type) {
  1588. case "input":
  1589. if (skipInputEvent === true) {
  1590. skipInputEvent = false;
  1591. return e.preventDefault();
  1592. }
  1593. if (mobile) {
  1594. var args = arguments;
  1595. setTimeout(function() {
  1596. eventHandler.apply(that, args);
  1597. caret(that, that.inputmask.caretPos, undefined, true);
  1598. }, 0);
  1599. return false;
  1600. }
  1601. break;
  1602. case "keydown":
  1603. skipKeyPressEvent = false;
  1604. skipInputEvent = false;
  1605. break;
  1606. case "keypress":
  1607. if (skipKeyPressEvent === true) {
  1608. return e.preventDefault();
  1609. }
  1610. skipKeyPressEvent = true;
  1611. break;
  1612. case "click":
  1613. if (iemobile || iphone) {
  1614. var args = arguments;
  1615. setTimeout(function() {
  1616. eventHandler.apply(that, args);
  1617. }, 0);
  1618. return false;
  1619. }
  1620. break;
  1621. }
  1622. var returnVal = eventHandler.apply(that, arguments);
  1623. if (returnVal === false) {
  1624. e.preventDefault();
  1625. e.stopPropagation();
  1626. }
  1627. return returnVal;
  1628. }
  1629. };
  1630. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1631. input.inputmask.events[eventName].push(ev);
  1632. if ($.inArray(eventName, [ "submit", "reset" ]) !== -1) {
  1633. if (input.form !== null) $(input.form).on(eventName, ev);
  1634. } else {
  1635. $(input).on(eventName, ev);
  1636. }
  1637. },
  1638. off: function(input, event) {
  1639. if (input.inputmask && input.inputmask.events) {
  1640. var events;
  1641. if (event) {
  1642. events = [];
  1643. events[event] = input.inputmask.events[event];
  1644. } else {
  1645. events = input.inputmask.events;
  1646. }
  1647. $.each(events, function(eventName, evArr) {
  1648. while (evArr.length > 0) {
  1649. var ev = evArr.pop();
  1650. if ($.inArray(eventName, [ "submit", "reset" ]) !== -1) {
  1651. if (input.form !== null) $(input.form).off(eventName, ev);
  1652. } else {
  1653. $(input).off(eventName, ev);
  1654. }
  1655. }
  1656. delete input.inputmask.events[eventName];
  1657. });
  1658. }
  1659. }
  1660. };
  1661. var EventHandlers = {
  1662. keydownEvent: function(e) {
  1663. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1664. if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI || e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut")) {
  1665. e.preventDefault();
  1666. handleRemove(input, k, pos);
  1667. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  1668. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) {
  1669. e.preventDefault();
  1670. var caretPos = seekNext(getLastValidPosition());
  1671. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  1672. } else if (k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP) {
  1673. e.preventDefault();
  1674. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  1675. } else if ((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || k === 90 && e.ctrlKey) && e.altKey !== true) {
  1676. checkVal(input, true, false, undoValue.split(""));
  1677. $input.trigger("click");
  1678. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) {
  1679. opts.insertMode = !opts.insertMode;
  1680. input.setAttribute("im-insert", opts.insertMode);
  1681. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  1682. if (e.shiftKey === true) {
  1683. if (getTest(pos.begin).match.fn === null) {
  1684. pos.begin = seekNext(pos.begin);
  1685. }
  1686. pos.end = seekPrevious(pos.begin, true);
  1687. pos.begin = seekPrevious(pos.end, true);
  1688. } else {
  1689. pos.begin = seekNext(pos.begin, true);
  1690. pos.end = seekNext(pos.begin, true);
  1691. if (pos.end < getMaskSet().maskLength) pos.end--;
  1692. }
  1693. if (pos.begin < getMaskSet().maskLength) {
  1694. e.preventDefault();
  1695. caret(input, pos.begin, pos.end);
  1696. }
  1697. }
  1698. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  1699. ignorable = $.inArray(k, opts.ignorables) !== -1;
  1700. },
  1701. keypressEvent: function(e, checkval, writeOut, strict, ndx) {
  1702. var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode;
  1703. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1704. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  1705. undoValue = getBuffer().join("");
  1706. setTimeout(function() {
  1707. $input.trigger("change");
  1708. }, 0);
  1709. }
  1710. return true;
  1711. } else {
  1712. if (k) {
  1713. if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
  1714. var pos = checkval ? {
  1715. begin: ndx,
  1716. end: ndx
  1717. } : caret(input), forwardPosition, c = String.fromCharCode(k), offset = 0;
  1718. if (opts._radixDance && opts.numericInput) {
  1719. var caretPos = getBuffer().indexOf(opts.radixPoint.charAt(0)) + 1;
  1720. if (pos.begin <= caretPos) {
  1721. if (k === opts.radixPoint.charCodeAt(0)) offset = 1;
  1722. pos.begin -= 1;
  1723. pos.end -= 1;
  1724. }
  1725. }
  1726. getMaskSet().writeOutBuffer = true;
  1727. var valResult = isValid(pos, c, strict);
  1728. if (valResult !== false) {
  1729. resetMaskSet(true);
  1730. forwardPosition = valResult.caret !== undefined ? valResult.caret : seekNext(valResult.pos.begin ? valResult.pos.begin : valResult.pos);
  1731. getMaskSet().p = forwardPosition;
  1732. }
  1733. forwardPosition = (opts.numericInput && valResult.caret === undefined ? seekPrevious(forwardPosition) : forwardPosition) + offset;
  1734. if (writeOut !== false) {
  1735. setTimeout(function() {
  1736. opts.onKeyValidation.call(input, k, valResult, opts);
  1737. }, 0);
  1738. if (getMaskSet().writeOutBuffer && valResult !== false) {
  1739. var buffer = getBuffer();
  1740. writeBuffer(input, buffer, forwardPosition, e, checkval !== true);
  1741. }
  1742. }
  1743. e.preventDefault();
  1744. if (checkval) {
  1745. if (valResult !== false) valResult.forwardPosition = forwardPosition;
  1746. return valResult;
  1747. }
  1748. }
  1749. }
  1750. },
  1751. pasteEvent: function(e) {
  1752. var input = this, ev = e.originalEvent || e, $input = $(input), inputValue = input.inputmask._valueGet(true), caretPos = caret(input), tempValue;
  1753. if (isRTL) {
  1754. tempValue = caretPos.end;
  1755. caretPos.end = caretPos.begin;
  1756. caretPos.begin = tempValue;
  1757. }
  1758. var valueBeforeCaret = inputValue.substr(0, caretPos.begin), valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  1759. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  1760. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  1761. if (window.clipboardData && window.clipboardData.getData) {
  1762. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  1763. } else if (ev.clipboardData && ev.clipboardData.getData) {
  1764. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  1765. } else return true;
  1766. var pasteValue = inputValue;
  1767. if ($.isFunction(opts.onBeforePaste)) {
  1768. pasteValue = opts.onBeforePaste.call(inputmask, inputValue, opts);
  1769. if (pasteValue === false) {
  1770. return e.preventDefault();
  1771. }
  1772. if (!pasteValue) {
  1773. pasteValue = inputValue;
  1774. }
  1775. }
  1776. checkVal(input, false, false, pasteValue.toString().split(""));
  1777. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  1778. return e.preventDefault();
  1779. },
  1780. inputFallBackEvent: function(e) {
  1781. function radixPointHandler(input, inputValue, caretPos) {
  1782. if (inputValue.charAt(caretPos.begin - 1) === "." && opts.radixPoint !== "") {
  1783. inputValue = inputValue.split("");
  1784. inputValue[caretPos.begin - 1] = opts.radixPoint.charAt(0);
  1785. inputValue = inputValue.join("");
  1786. }
  1787. return inputValue;
  1788. }
  1789. function ieMobileHandler(input, inputValue, caretPos) {
  1790. if (iemobile) {
  1791. var inputChar = inputValue.replace(getBuffer().join(""), "");
  1792. if (inputChar.length === 1) {
  1793. var iv = inputValue.split("");
  1794. iv.splice(caretPos.begin, 0, inputChar);
  1795. inputValue = iv.join("");
  1796. }
  1797. }
  1798. return inputValue;
  1799. }
  1800. var input = this, inputValue = input.inputmask._valueGet();
  1801. if (getBuffer().join("") !== inputValue) {
  1802. var caretPos = caret(input);
  1803. inputValue = radixPointHandler(input, inputValue, caretPos);
  1804. inputValue = ieMobileHandler(input, inputValue, caretPos);
  1805. if (getBuffer().join("") !== inputValue) {
  1806. var buffer = getBuffer().join(""), offset = !opts.numericInput && inputValue.length > buffer.length ? -1 : 0, frontPart = inputValue.substr(0, caretPos.begin), backPart = inputValue.substr(caretPos.begin), frontBufferPart = buffer.substr(0, caretPos.begin + offset), backBufferPart = buffer.substr(caretPos.begin + offset);
  1807. var selection = caretPos, entries = "", isEntry = false;
  1808. if (frontPart !== frontBufferPart) {
  1809. var fpl = (isEntry = frontPart.length >= frontBufferPart.length) ? frontPart.length : frontBufferPart.length, i;
  1810. for (i = 0; frontPart.charAt(i) === frontBufferPart.charAt(i) && i < fpl; i++) ;
  1811. if (isEntry) {
  1812. selection.begin = i - offset;
  1813. entries += frontPart.slice(i, selection.end);
  1814. }
  1815. }
  1816. if (backPart !== backBufferPart) {
  1817. if (backPart.length > backBufferPart.length) {
  1818. entries += backPart.slice(0, 1);
  1819. } else {
  1820. if (backPart.length < backBufferPart.length) {
  1821. selection.end += backBufferPart.length - backPart.length;
  1822. if (!isEntry && opts.radixPoint !== "" && backPart === "" && frontPart.charAt(selection.begin + offset - 1) === opts.radixPoint) {
  1823. selection.begin--;
  1824. entries = opts.radixPoint;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. writeBuffer(input, getBuffer(), {
  1830. begin: selection.begin + offset,
  1831. end: selection.end + offset
  1832. });
  1833. if (entries.length > 0) {
  1834. $.each(entries.split(""), function(ndx, entry) {
  1835. var keypress = new $.Event("keypress");
  1836. keypress.which = entry.charCodeAt(0);
  1837. ignorable = false;
  1838. EventHandlers.keypressEvent.call(input, keypress);
  1839. });
  1840. } else {
  1841. if (selection.begin === selection.end - 1) {
  1842. selection.begin = seekPrevious(selection.begin + 1);
  1843. if (selection.begin === selection.end - 1) {
  1844. caret(input, selection.begin);
  1845. } else {
  1846. caret(input, selection.begin, selection.end);
  1847. }
  1848. }
  1849. var keydown = new $.Event("keydown");
  1850. keydown.keyCode = opts.numericInput ? Inputmask.keyCode.BACKSPACE : Inputmask.keyCode.DELETE;
  1851. EventHandlers.keydownEvent.call(input, keydown);
  1852. }
  1853. e.preventDefault();
  1854. }
  1855. }
  1856. },
  1857. beforeInputEvent: function(e) {
  1858. if (e.cancelable) {
  1859. var input = this;
  1860. switch (e.inputType) {
  1861. case "insertText":
  1862. $.each(e.data.split(""), function(ndx, entry) {
  1863. var keypress = new $.Event("keypress");
  1864. keypress.which = entry.charCodeAt(0);
  1865. ignorable = false;
  1866. EventHandlers.keypressEvent.call(input, keypress);
  1867. });
  1868. return e.preventDefault();
  1869. case "deleteContentBackward":
  1870. var keydown = new $.Event("keydown");
  1871. keydown.keyCode = Inputmask.keyCode.BACKSPACE;
  1872. EventHandlers.keydownEvent.call(input, keydown);
  1873. return e.preventDefault();
  1874. case "deleteContentForward":
  1875. var keydown = new $.Event("keydown");
  1876. keydown.keyCode = Inputmask.keyCode.DELETE;
  1877. EventHandlers.keydownEvent.call(input, keydown);
  1878. return e.preventDefault();
  1879. }
  1880. }
  1881. },
  1882. setValueEvent: function(e) {
  1883. this.inputmask.refreshValue = false;
  1884. var input = this, value = e && e.detail ? e.detail[0] : arguments[1], value = value || input.inputmask._valueGet(true);
  1885. if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask.call(inputmask, value, opts) || value;
  1886. value = value.split("");
  1887. checkVal(input, true, false, value);
  1888. undoValue = getBuffer().join("");
  1889. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  1890. input.inputmask._valueSet("");
  1891. }
  1892. },
  1893. focusEvent: function(e) {
  1894. var input = this, nptValue = input.inputmask._valueGet();
  1895. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || opts.showMaskOnHover && nptValue === "")) {
  1896. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  1897. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1898. } else if (mouseEnter === false) {
  1899. caret(input, seekNext(getLastValidPosition()));
  1900. }
  1901. }
  1902. if (opts.positionCaretOnTab === true && mouseEnter === false) {
  1903. EventHandlers.clickEvent.apply(input, [ e, true ]);
  1904. }
  1905. undoValue = getBuffer().join("");
  1906. },
  1907. mouseleaveEvent: function(e) {
  1908. var input = this;
  1909. mouseEnter = false;
  1910. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  1911. HandleNativePlaceholder(input, originalPlaceholder);
  1912. }
  1913. },
  1914. clickEvent: function(e, tabbed) {
  1915. function doRadixFocus(clickPos) {
  1916. if (opts.radixPoint !== "") {
  1917. var vps = getMaskSet().validPositions;
  1918. if (vps[clickPos] === undefined || vps[clickPos].input === getPlaceholder(clickPos)) {
  1919. if (clickPos < seekNext(-1)) return true;
  1920. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  1921. if (radixPos !== -1) {
  1922. for (var vp in vps) {
  1923. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  1924. return false;
  1925. }
  1926. }
  1927. return true;
  1928. }
  1929. }
  1930. }
  1931. return false;
  1932. }
  1933. var input = this;
  1934. setTimeout(function() {
  1935. if (document.activeElement === input) {
  1936. var selectedCaret = caret(input);
  1937. if (tabbed) {
  1938. if (isRTL) {
  1939. selectedCaret.end = selectedCaret.begin;
  1940. } else {
  1941. selectedCaret.begin = selectedCaret.end;
  1942. }
  1943. }
  1944. if (selectedCaret.begin === selectedCaret.end) {
  1945. switch (opts.positionCaretOnClick) {
  1946. case "none":
  1947. break;
  1948. case "select":
  1949. caret(input, 0, getBuffer().length);
  1950. break;
  1951. case "ignore":
  1952. caret(input, seekNext(getLastValidPosition()));
  1953. break;
  1954. case "radixFocus":
  1955. if (doRadixFocus(selectedCaret.begin)) {
  1956. var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
  1957. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  1958. break;
  1959. }
  1960. default:
  1961. var clickPosition = selectedCaret.begin, lvclickPosition = getLastValidPosition(clickPosition, true), lastPosition = seekNext(lvclickPosition);
  1962. if (clickPosition < lastPosition) {
  1963. caret(input, !isMask(clickPosition, true) && !isMask(clickPosition - 1, true) ? seekNext(clickPosition) : clickPosition);
  1964. } else {
  1965. var lvp = getMaskSet().validPositions[lvclickPosition], tt = getTestTemplate(lastPosition, lvp ? lvp.match.locator : undefined, lvp), placeholder = getPlaceholder(lastPosition, tt.match);
  1966. if (placeholder !== "" && getBuffer()[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true || !isMask(lastPosition, opts.keepStatic) && tt.match.def === placeholder) {
  1967. var newPos = seekNext(lastPosition);
  1968. if (clickPosition >= newPos || clickPosition === lastPosition) {
  1969. lastPosition = newPos;
  1970. }
  1971. }
  1972. caret(input, lastPosition);
  1973. }
  1974. break;
  1975. }
  1976. }
  1977. }
  1978. }, 0);
  1979. },
  1980. cutEvent: function(e) {
  1981. var input = this, $input = $(input), pos = caret(input), ev = e.originalEvent || e;
  1982. var clipboardData = window.clipboardData || ev.clipboardData, clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  1983. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  1984. if (document.execCommand) document.execCommand("copy");
  1985. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  1986. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  1987. },
  1988. blurEvent: function(e) {
  1989. var $input = $(this), input = this;
  1990. if (input.inputmask) {
  1991. HandleNativePlaceholder(input, originalPlaceholder);
  1992. var nptValue = input.inputmask._valueGet(), buffer = getBuffer().slice();
  1993. if (nptValue !== "" || colorMask !== undefined) {
  1994. if (opts.clearMaskOnLostFocus) {
  1995. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  1996. buffer = [];
  1997. } else {
  1998. clearOptionalTail(buffer);
  1999. }
  2000. }
  2001. if (isComplete(buffer) === false) {
  2002. setTimeout(function() {
  2003. $input.trigger("incomplete");
  2004. }, 0);
  2005. if (opts.clearIncomplete) {
  2006. resetMaskSet();
  2007. if (opts.clearMaskOnLostFocus) {
  2008. buffer = [];
  2009. } else {
  2010. buffer = getBufferTemplate().slice();
  2011. }
  2012. }
  2013. }
  2014. writeBuffer(input, buffer, undefined, e);
  2015. }
  2016. if (undoValue !== getBuffer().join("")) {
  2017. undoValue = buffer.join("");
  2018. $input.trigger("change");
  2019. }
  2020. }
  2021. },
  2022. mouseenterEvent: function(e) {
  2023. var input = this;
  2024. mouseEnter = true;
  2025. if (document.activeElement !== input && opts.showMaskOnHover) {
  2026. HandleNativePlaceholder(input, (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""));
  2027. }
  2028. },
  2029. submitEvent: function(e) {
  2030. if (undoValue !== getBuffer().join("")) {
  2031. $el.trigger("change");
  2032. }
  2033. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2034. el.inputmask._valueSet("");
  2035. }
  2036. if (opts.clearIncomplete && isComplete(getBuffer()) === false) {
  2037. el.inputmask._valueSet("");
  2038. }
  2039. if (opts.removeMaskOnSubmit) {
  2040. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2041. setTimeout(function() {
  2042. writeBuffer(el, getBuffer());
  2043. }, 0);
  2044. }
  2045. },
  2046. resetEvent: function(e) {
  2047. el.inputmask.refreshValue = true;
  2048. setTimeout(function() {
  2049. $el.trigger("setvalue");
  2050. }, 0);
  2051. }
  2052. };
  2053. function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
  2054. var inputmask = this || input.inputmask, inputValue = nptvl.slice(), charCodes = "", initialNdx = -1, result = undefined;
  2055. function isTemplateMatch(ndx, charCodes) {
  2056. var charCodeNdx = getMaskTemplate(true, 0, false).slice(ndx, seekNext(ndx)).join("").replace(/'/g, "").indexOf(charCodes);
  2057. return charCodeNdx !== -1 && !isMask(ndx) && (getTest(ndx).match.nativeDef === charCodes.charAt(0) || getTest(ndx).match.fn === null && getTest(ndx).match.nativeDef === "'" + charCodes.charAt(0) || getTest(ndx).match.nativeDef === " " && (getTest(ndx + 1).match.nativeDef === charCodes.charAt(0) || getTest(ndx + 1).match.fn === null && getTest(ndx + 1).match.nativeDef === "'" + charCodes.charAt(0)));
  2058. }
  2059. resetMaskSet();
  2060. if (!strict && opts.autoUnmask !== true) {
  2061. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""), matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  2062. if (matches && matches.length > 0) {
  2063. inputValue.splice(0, matches.length * staticInput.length);
  2064. initialNdx = seekNext(initialNdx);
  2065. }
  2066. } else {
  2067. initialNdx = seekNext(initialNdx);
  2068. }
  2069. if (initialNdx === -1) {
  2070. getMaskSet().p = seekNext(initialNdx);
  2071. initialNdx = 0;
  2072. } else getMaskSet().p = initialNdx;
  2073. inputmask.caretPos = {
  2074. begin: initialNdx
  2075. };
  2076. $.each(inputValue, function(ndx, charCode) {
  2077. if (charCode !== undefined) {
  2078. if (getMaskSet().validPositions[ndx] === undefined && inputValue[ndx] === getPlaceholder(ndx) && isMask(ndx, true) && isValid(ndx, inputValue[ndx], true, undefined, undefined, true) === false) {
  2079. getMaskSet().p++;
  2080. } else {
  2081. var keypress = new $.Event("_checkval");
  2082. keypress.which = charCode.charCodeAt(0);
  2083. charCodes += charCode;
  2084. var lvp = getLastValidPosition(undefined, true);
  2085. if (!isTemplateMatch(initialNdx, charCodes)) {
  2086. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, inputmask.caretPos.begin);
  2087. if (result) {
  2088. initialNdx = inputmask.caretPos.begin + 1;
  2089. charCodes = "";
  2090. }
  2091. } else {
  2092. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, lvp + 1);
  2093. }
  2094. if (result) {
  2095. writeBuffer(undefined, getBuffer(), result.forwardPosition, keypress, false);
  2096. inputmask.caretPos = {
  2097. begin: result.forwardPosition,
  2098. end: result.forwardPosition
  2099. };
  2100. }
  2101. }
  2102. }
  2103. });
  2104. if (writeOut) writeBuffer(input, getBuffer(), result ? result.forwardPosition : undefined, initiatingEvent || new $.Event("checkval"), initiatingEvent && initiatingEvent.type === "input");
  2105. }
  2106. function unmaskedvalue(input) {
  2107. if (input) {
  2108. if (input.inputmask === undefined) {
  2109. return input.value;
  2110. }
  2111. if (input.inputmask && input.inputmask.refreshValue) {
  2112. EventHandlers.setValueEvent.call(input);
  2113. }
  2114. }
  2115. var umValue = [], vps = getMaskSet().validPositions;
  2116. for (var pndx in vps) {
  2117. if (vps[pndx].match && vps[pndx].match.fn != null) {
  2118. umValue.push(vps[pndx].input);
  2119. }
  2120. }
  2121. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  2122. if ($.isFunction(opts.onUnMask)) {
  2123. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  2124. unmaskedValue = opts.onUnMask.call(inputmask, bufferValue, unmaskedValue, opts);
  2125. }
  2126. return unmaskedValue;
  2127. }
  2128. function caret(input, begin, end, notranslate) {
  2129. function translatePosition(pos) {
  2130. if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "") && el) {
  2131. pos = el.inputmask._valueGet().length - pos;
  2132. }
  2133. return pos;
  2134. }
  2135. var range;
  2136. if (begin !== undefined) {
  2137. if ($.isArray(begin)) {
  2138. end = isRTL ? begin[0] : begin[1];
  2139. begin = isRTL ? begin[1] : begin[0];
  2140. }
  2141. if (begin.begin !== undefined) {
  2142. end = isRTL ? begin.begin : begin.end;
  2143. begin = isRTL ? begin.end : begin.begin;
  2144. }
  2145. if (typeof begin === "number") {
  2146. begin = notranslate ? begin : translatePosition(begin);
  2147. end = notranslate ? end : translatePosition(end);
  2148. end = typeof end == "number" ? end : begin;
  2149. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  2150. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  2151. input.inputmask.caretPos = {
  2152. begin: begin,
  2153. end: end
  2154. };
  2155. if (input === document.activeElement) {
  2156. if ("selectionStart" in input) {
  2157. input.selectionStart = begin;
  2158. input.selectionEnd = end;
  2159. } else if (window.getSelection) {
  2160. range = document.createRange();
  2161. if (input.firstChild === undefined || input.firstChild === null) {
  2162. var textNode = document.createTextNode("");
  2163. input.appendChild(textNode);
  2164. }
  2165. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  2166. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  2167. range.collapse(true);
  2168. var sel = window.getSelection();
  2169. sel.removeAllRanges();
  2170. sel.addRange(range);
  2171. } else if (input.createTextRange) {
  2172. range = input.createTextRange();
  2173. range.collapse(true);
  2174. range.moveEnd("character", end);
  2175. range.moveStart("character", begin);
  2176. range.select();
  2177. }
  2178. renderColorMask(input, {
  2179. begin: begin,
  2180. end: end
  2181. });
  2182. }
  2183. }
  2184. } else {
  2185. if ("selectionStart" in input) {
  2186. begin = input.selectionStart;
  2187. end = input.selectionEnd;
  2188. } else if (window.getSelection) {
  2189. range = window.getSelection().getRangeAt(0);
  2190. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  2191. begin = range.startOffset;
  2192. end = range.endOffset;
  2193. }
  2194. } else if (document.selection && document.selection.createRange) {
  2195. range = document.selection.createRange();
  2196. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  2197. end = begin + range.text.length;
  2198. }
  2199. return {
  2200. begin: notranslate ? begin : translatePosition(begin),
  2201. end: notranslate ? end : translatePosition(end)
  2202. };
  2203. }
  2204. }
  2205. function determineLastRequiredPosition(returnDefinition) {
  2206. var buffer = getMaskTemplate(true, getLastValidPosition(), true, true), bl = buffer.length, pos, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp], ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined, testPos;
  2207. for (pos = lvp + 1; pos < buffer.length; pos++) {
  2208. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2209. ndxIntlzr = testPos.locator.slice();
  2210. positions[pos] = $.extend(true, {}, testPos);
  2211. }
  2212. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  2213. for (pos = bl - 1; pos > lvp; pos--) {
  2214. testPos = positions[pos];
  2215. if ((testPos.match.optionality || testPos.match.optionalQuantifier && testPos.match.newBlockMarker || lvTestAlt && (lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null || testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")) && buffer[pos] === getPlaceholder(pos, testPos.match)) {
  2216. bl--;
  2217. } else break;
  2218. }
  2219. return returnDefinition ? {
  2220. l: bl,
  2221. def: positions[bl] ? positions[bl].match : undefined
  2222. } : bl;
  2223. }
  2224. function clearOptionalTail(buffer) {
  2225. buffer.length = 0;
  2226. var template = getMaskTemplate(true, 0, true, undefined, true), lmnt, validPos;
  2227. while (lmnt = template.shift(), lmnt !== undefined) buffer.push(lmnt);
  2228. return buffer;
  2229. }
  2230. function isComplete(buffer) {
  2231. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  2232. if (opts.repeat === "*") return undefined;
  2233. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp.l);
  2234. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  2235. complete = true;
  2236. for (var i = 0; i <= aml; i++) {
  2237. var test = getTestTemplate(i).match;
  2238. if (test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true || test.fn === null && buffer[i] !== getPlaceholder(i, test)) {
  2239. complete = false;
  2240. break;
  2241. }
  2242. }
  2243. }
  2244. return complete;
  2245. }
  2246. function handleRemove(input, k, pos, strict, fromIsValid) {
  2247. if (opts.numericInput || isRTL) {
  2248. if (k === Inputmask.keyCode.BACKSPACE) {
  2249. k = Inputmask.keyCode.DELETE;
  2250. } else if (k === Inputmask.keyCode.DELETE) {
  2251. k = Inputmask.keyCode.BACKSPACE;
  2252. }
  2253. if (isRTL) {
  2254. var pend = pos.end;
  2255. pos.end = pos.begin;
  2256. pos.begin = pend;
  2257. }
  2258. }
  2259. if (k === Inputmask.keyCode.BACKSPACE && pos.end - pos.begin < 1) {
  2260. pos.begin = seekPrevious(pos.begin);
  2261. if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
  2262. pos.begin--;
  2263. }
  2264. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  2265. pos.end = isMask(pos.end, true) && (getMaskSet().validPositions[pos.end] && getMaskSet().validPositions[pos.end].input !== opts.radixPoint) ? pos.end + 1 : seekNext(pos.end) + 1;
  2266. if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
  2267. pos.end++;
  2268. }
  2269. }
  2270. revalidateMask(pos);
  2271. if (strict !== true && opts.keepStatic !== false || opts.regex !== null) {
  2272. var result = alternate(true);
  2273. if (result) {
  2274. var newPos = result.caret !== undefined ? result.caret : result.pos ? seekNext(result.pos.begin ? result.pos.begin : result.pos) : getLastValidPosition(-1, true);
  2275. if (k !== Inputmask.keyCode.DELETE || pos.begin > newPos) {
  2276. pos.begin == newPos;
  2277. }
  2278. }
  2279. }
  2280. var lvp = getLastValidPosition(pos.begin, true);
  2281. if (lvp < pos.begin || pos.begin === -1) {
  2282. getMaskSet().p = seekNext(lvp);
  2283. } else if (strict !== true) {
  2284. getMaskSet().p = pos.begin;
  2285. if (fromIsValid !== true) {
  2286. while (getMaskSet().p < lvp && getMaskSet().validPositions[getMaskSet().p] === undefined) {
  2287. getMaskSet().p++;
  2288. }
  2289. }
  2290. }
  2291. }
  2292. function initializeColorMask(input) {
  2293. var computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2294. function findCaretPos(clientx) {
  2295. var e = document.createElement("span"), caretPos;
  2296. for (var style in computedStyle) {
  2297. if (isNaN(style) && style.indexOf("font") !== -1) {
  2298. e.style[style] = computedStyle[style];
  2299. }
  2300. }
  2301. e.style.textTransform = computedStyle.textTransform;
  2302. e.style.letterSpacing = computedStyle.letterSpacing;
  2303. e.style.position = "absolute";
  2304. e.style.height = "auto";
  2305. e.style.width = "auto";
  2306. e.style.visibility = "hidden";
  2307. e.style.whiteSpace = "nowrap";
  2308. document.body.appendChild(e);
  2309. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2310. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2311. e.innerHTML += inputText.charAt(caretPos) || "_";
  2312. if (e.offsetWidth >= clientx) {
  2313. var offset1 = clientx - previousWidth;
  2314. var offset2 = e.offsetWidth - clientx;
  2315. e.innerHTML = inputText.charAt(caretPos);
  2316. offset1 -= e.offsetWidth / 3;
  2317. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2318. break;
  2319. }
  2320. previousWidth = e.offsetWidth;
  2321. }
  2322. document.body.removeChild(e);
  2323. return caretPos;
  2324. }
  2325. var template = document.createElement("div");
  2326. template.style.width = computedStyle.width;
  2327. template.style.textAlign = computedStyle.textAlign;
  2328. colorMask = document.createElement("div");
  2329. input.inputmask.colorMask = colorMask;
  2330. colorMask.className = "im-colormask";
  2331. input.parentNode.insertBefore(colorMask, input);
  2332. input.parentNode.removeChild(input);
  2333. colorMask.appendChild(input);
  2334. colorMask.appendChild(template);
  2335. input.style.left = template.offsetLeft + "px";
  2336. $(colorMask).on("mouseleave", function(e) {
  2337. return EventHandlers.mouseleaveEvent.call(input, [ e ]);
  2338. });
  2339. $(colorMask).on("mouseenter", function(e) {
  2340. return EventHandlers.mouseenterEvent.call(input, [ e ]);
  2341. });
  2342. $(colorMask).on("click", function(e) {
  2343. caret(input, findCaretPos(e.clientX));
  2344. return EventHandlers.clickEvent.call(input, [ e ]);
  2345. });
  2346. }
  2347. Inputmask.prototype.positionColorMask = function(input, template) {
  2348. input.style.left = template.offsetLeft + "px";
  2349. };
  2350. function renderColorMask(input, caretPos, clear) {
  2351. var maskTemplate = [], isStatic = false, test, testPos, ndxIntlzr, pos = 0;
  2352. function setEntry(entry) {
  2353. if (entry === undefined) entry = "";
  2354. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2355. isStatic = true;
  2356. maskTemplate.push("<span class='im-static'>" + entry);
  2357. } else if (isStatic && (test.fn !== null && testPos.input !== undefined || test.def === "")) {
  2358. isStatic = false;
  2359. var mtl = maskTemplate.length;
  2360. maskTemplate[mtl - 1] = maskTemplate[mtl - 1] + "</span>";
  2361. maskTemplate.push(entry);
  2362. } else maskTemplate.push(entry);
  2363. }
  2364. function setCaret() {
  2365. if (document.activeElement === input) {
  2366. maskTemplate.splice(caretPos.begin, 0, caretPos.begin === caretPos.end || caretPos.end > getMaskSet().maskLength ? '<mark class="im-caret" style="border-right-width: 1px;border-right-style: solid;">' : '<mark class="im-caret-select">');
  2367. maskTemplate.splice(caretPos.end + 1, 0, "</mark>");
  2368. }
  2369. }
  2370. if (colorMask !== undefined) {
  2371. var buffer = getBuffer();
  2372. if (caretPos === undefined) {
  2373. caretPos = caret(input);
  2374. } else if (caretPos.begin === undefined) {
  2375. caretPos = {
  2376. begin: caretPos,
  2377. end: caretPos
  2378. };
  2379. }
  2380. if (clear !== true) {
  2381. var lvp = getLastValidPosition();
  2382. do {
  2383. if (getMaskSet().validPositions[pos]) {
  2384. testPos = getMaskSet().validPositions[pos];
  2385. test = testPos.match;
  2386. ndxIntlzr = testPos.locator.slice();
  2387. setEntry(buffer[pos]);
  2388. } else {
  2389. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2390. test = testPos.match;
  2391. ndxIntlzr = testPos.locator.slice();
  2392. if (opts.jitMasking === false || pos < lvp || typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos) {
  2393. setEntry(getPlaceholder(pos, test));
  2394. } else isStatic = false;
  2395. }
  2396. pos++;
  2397. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos || isStatic);
  2398. if (isStatic) setEntry();
  2399. setCaret();
  2400. }
  2401. var template = colorMask.getElementsByTagName("div")[0];
  2402. template.innerHTML = maskTemplate.join("");
  2403. input.inputmask.positionColorMask(input, template);
  2404. }
  2405. }
  2406. function mask(elem) {
  2407. function isElementTypeSupported(input, opts) {
  2408. function patchValueProperty(npt) {
  2409. var valueGet;
  2410. var valueSet;
  2411. function patchValhook(type) {
  2412. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2413. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
  2414. return elem.value;
  2415. };
  2416. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
  2417. elem.value = value;
  2418. return elem;
  2419. };
  2420. $.valHooks[type] = {
  2421. get: function(elem) {
  2422. if (elem.inputmask) {
  2423. if (elem.inputmask.opts.autoUnmask) {
  2424. return elem.inputmask.unmaskedvalue();
  2425. } else {
  2426. var result = valhookGet(elem);
  2427. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2428. }
  2429. } else return valhookGet(elem);
  2430. },
  2431. set: function(elem, value) {
  2432. var $elem = $(elem), result;
  2433. result = valhookSet(elem, value);
  2434. if (elem.inputmask) {
  2435. $elem.trigger("setvalue", [ value ]);
  2436. }
  2437. return result;
  2438. },
  2439. inputmaskpatch: true
  2440. };
  2441. }
  2442. }
  2443. function getter() {
  2444. if (this.inputmask) {
  2445. return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : getLastValidPosition() !== -1 || opts.nullable !== true ? document.activeElement === this && opts.clearMaskOnLostFocus ? (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") : valueGet.call(this) : "";
  2446. } else return valueGet.call(this);
  2447. }
  2448. function setter(value) {
  2449. valueSet.call(this, value);
  2450. if (this.inputmask) {
  2451. $(this).trigger("setvalue", [ value ]);
  2452. }
  2453. }
  2454. function installNativeValueSetFallback(npt) {
  2455. EventRuler.on(npt, "mouseenter", function(event) {
  2456. var $input = $(this), input = this, value = input.inputmask._valueGet();
  2457. if (value !== getBuffer().join("")) {
  2458. $input.trigger("setvalue");
  2459. }
  2460. });
  2461. }
  2462. if (!npt.inputmask.__valueGet) {
  2463. if (opts.noValuePatching !== true) {
  2464. if (Object.getOwnPropertyDescriptor) {
  2465. if (typeof Object.getPrototypeOf !== "function") {
  2466. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function(object) {
  2467. return object.__proto__;
  2468. } : function(object) {
  2469. return object.constructor.prototype;
  2470. };
  2471. }
  2472. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2473. if (valueProperty && valueProperty.get && valueProperty.set) {
  2474. valueGet = valueProperty.get;
  2475. valueSet = valueProperty.set;
  2476. Object.defineProperty(npt, "value", {
  2477. get: getter,
  2478. set: setter,
  2479. configurable: true
  2480. });
  2481. } else if (npt.tagName !== "INPUT") {
  2482. valueGet = function() {
  2483. return this.textContent;
  2484. };
  2485. valueSet = function(value) {
  2486. this.textContent = value;
  2487. };
  2488. Object.defineProperty(npt, "value", {
  2489. get: getter,
  2490. set: setter,
  2491. configurable: true
  2492. });
  2493. }
  2494. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2495. valueGet = npt.__lookupGetter__("value");
  2496. valueSet = npt.__lookupSetter__("value");
  2497. npt.__defineGetter__("value", getter);
  2498. npt.__defineSetter__("value", setter);
  2499. }
  2500. npt.inputmask.__valueGet = valueGet;
  2501. npt.inputmask.__valueSet = valueSet;
  2502. }
  2503. npt.inputmask._valueGet = function(overruleRTL) {
  2504. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2505. };
  2506. npt.inputmask._valueSet = function(value, overruleRTL) {
  2507. valueSet.call(this.el, value === null || value === undefined ? "" : overruleRTL !== true && isRTL ? value.split("").reverse().join("") : value);
  2508. };
  2509. if (valueGet === undefined) {
  2510. valueGet = function() {
  2511. return this.value;
  2512. };
  2513. valueSet = function(value) {
  2514. this.value = value;
  2515. };
  2516. patchValhook(npt.type);
  2517. installNativeValueSetFallback(npt);
  2518. }
  2519. }
  2520. }
  2521. var elementType = input.getAttribute("type");
  2522. var isSupported = input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1 || input.isContentEditable || input.tagName === "TEXTAREA";
  2523. if (!isSupported) {
  2524. if (input.tagName === "INPUT") {
  2525. var el = document.createElement("input");
  2526. el.setAttribute("type", elementType);
  2527. isSupported = el.type === "text";
  2528. el = null;
  2529. } else isSupported = "partial";
  2530. }
  2531. if (isSupported !== false) {
  2532. patchValueProperty(input);
  2533. } else input.inputmask = undefined;
  2534. return isSupported;
  2535. }
  2536. EventRuler.off(elem);
  2537. var isSupported = isElementTypeSupported(elem, opts);
  2538. if (isSupported !== false) {
  2539. el = elem;
  2540. $el = $(el);
  2541. originalPlaceholder = el.placeholder;
  2542. maxLength = el !== undefined ? el.maxLength : undefined;
  2543. if (maxLength === -1) maxLength = undefined;
  2544. if (opts.colorMask === true) {
  2545. initializeColorMask(el);
  2546. }
  2547. if (mobile) {
  2548. if ("inputmode" in el) {
  2549. el.inputmode = opts.inputmode;
  2550. el.setAttribute("inputmode", opts.inputmode);
  2551. }
  2552. if (opts.disablePredictiveText === true) {
  2553. if ("autocorrect" in el) {
  2554. el.autocorrect = false;
  2555. } else {
  2556. if (opts.colorMask !== true) {
  2557. initializeColorMask(el);
  2558. }
  2559. el.type = "password";
  2560. }
  2561. }
  2562. }
  2563. if (isSupported === true) {
  2564. el.setAttribute("im-insert", opts.insertMode);
  2565. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2566. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2567. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2568. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2569. if (opts.colorMask !== true) {
  2570. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2571. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2572. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2573. }
  2574. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2575. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2576. EventRuler.on(el, "complete", opts.oncomplete);
  2577. EventRuler.on(el, "incomplete", opts.onincomplete);
  2578. EventRuler.on(el, "cleared", opts.oncleared);
  2579. if (!mobile && opts.inputEventOnly !== true) {
  2580. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2581. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2582. } else {
  2583. el.removeAttribute("maxLength");
  2584. }
  2585. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2586. EventRuler.on(el, "beforeinput", EventHandlers.beforeInputEvent);
  2587. }
  2588. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2589. undoValue = getBufferTemplate().join("");
  2590. if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2591. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, el.inputmask._valueGet(true), opts) || el.inputmask._valueGet(true) : el.inputmask._valueGet(true);
  2592. if (initialValue !== "") checkVal(el, true, false, initialValue.split(""));
  2593. var buffer = getBuffer().slice();
  2594. undoValue = buffer.join("");
  2595. if (isComplete(buffer) === false) {
  2596. if (opts.clearIncomplete) {
  2597. resetMaskSet();
  2598. }
  2599. }
  2600. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2601. if (getLastValidPosition() === -1) {
  2602. buffer = [];
  2603. } else {
  2604. clearOptionalTail(buffer);
  2605. }
  2606. }
  2607. if (opts.clearMaskOnLostFocus === false || opts.showMaskOnFocus && document.activeElement === el || el.inputmask._valueGet(true) !== "") writeBuffer(el, buffer);
  2608. if (document.activeElement === el) {
  2609. caret(el, seekNext(getLastValidPosition()));
  2610. }
  2611. }
  2612. }
  2613. }
  2614. var valueBuffer;
  2615. if (actionObj !== undefined) {
  2616. switch (actionObj.action) {
  2617. case "isComplete":
  2618. el = actionObj.el;
  2619. return isComplete(getBuffer());
  2620. case "unmaskedvalue":
  2621. if (el === undefined || actionObj.value !== undefined) {
  2622. valueBuffer = actionObj.value;
  2623. valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, valueBuffer, opts) || valueBuffer : valueBuffer).split("");
  2624. checkVal.call(this, undefined, false, false, valueBuffer);
  2625. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(inputmask, undefined, getBuffer(), 0, opts);
  2626. }
  2627. return unmaskedvalue(el);
  2628. case "mask":
  2629. mask(el);
  2630. break;
  2631. case "format":
  2632. valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, actionObj.value, opts) || actionObj.value : actionObj.value).split("");
  2633. checkVal.call(this, undefined, true, false, valueBuffer);
  2634. if (actionObj.metadata) {
  2635. return {
  2636. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2637. metadata: maskScope.call(this, {
  2638. action: "getmetadata"
  2639. }, maskset, opts)
  2640. };
  2641. }
  2642. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2643. case "isValid":
  2644. if (actionObj.value) {
  2645. valueBuffer = actionObj.value.split("");
  2646. checkVal.call(this, undefined, true, true, valueBuffer);
  2647. } else {
  2648. actionObj.value = getBuffer().join("");
  2649. }
  2650. var buffer = getBuffer();
  2651. var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
  2652. for (;lmib > rl; lmib--) {
  2653. if (isMask(lmib)) break;
  2654. }
  2655. buffer.splice(rl, lmib + 1 - rl);
  2656. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2657. case "getemptymask":
  2658. return getBufferTemplate().join("");
  2659. case "remove":
  2660. if (el && el.inputmask) {
  2661. $.data(el, "_inputmask_opts", null);
  2662. $el = $(el);
  2663. el.inputmask._valueSet(opts.autoUnmask ? unmaskedvalue(el) : el.inputmask._valueGet(true));
  2664. EventRuler.off(el);
  2665. if (el.inputmask.colorMask) {
  2666. colorMask = el.inputmask.colorMask;
  2667. colorMask.removeChild(el);
  2668. colorMask.parentNode.insertBefore(el, colorMask);
  2669. colorMask.parentNode.removeChild(colorMask);
  2670. }
  2671. var valueProperty;
  2672. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2673. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2674. if (valueProperty) {
  2675. if (el.inputmask.__valueGet) {
  2676. Object.defineProperty(el, "value", {
  2677. get: el.inputmask.__valueGet,
  2678. set: el.inputmask.__valueSet,
  2679. configurable: true
  2680. });
  2681. }
  2682. }
  2683. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2684. if (el.inputmask.__valueGet) {
  2685. el.__defineGetter__("value", el.inputmask.__valueGet);
  2686. el.__defineSetter__("value", el.inputmask.__valueSet);
  2687. }
  2688. }
  2689. el.inputmask = undefined;
  2690. }
  2691. return el;
  2692. break;
  2693. case "getmetadata":
  2694. if ($.isArray(maskset.metadata)) {
  2695. var maskTarget = getMaskTemplate(true, 0, false).join("");
  2696. $.each(maskset.metadata, function(ndx, mtdt) {
  2697. if (mtdt.mask === maskTarget) {
  2698. maskTarget = mtdt;
  2699. return false;
  2700. }
  2701. });
  2702. return maskTarget;
  2703. }
  2704. return maskset.metadata;
  2705. }
  2706. }
  2707. }
  2708. return Inputmask;
  2709. });