inputmask.js 146 KB

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