inputmask.js 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745
  1. /*!
  2. * inputmask.js
  3. * https://github.com/RobinHerbots/Inputmask
  4. * Copyright (c) 2010 - 2018 Robin Herbots
  5. * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. * Version: 4.0.5
  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. function importOption(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. function groupQuantifier(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. };
  555. Inputmask.extendDefaults = function(options) {
  556. $.extend(true, Inputmask.prototype.defaults, options);
  557. };
  558. Inputmask.extendDefinitions = function(definition) {
  559. $.extend(true, Inputmask.prototype.definitions, definition);
  560. };
  561. Inputmask.extendAliases = function(alias) {
  562. $.extend(true, Inputmask.prototype.aliases, alias);
  563. };
  564. Inputmask.format = function(value, options, metadata) {
  565. return Inputmask(options).format(value, metadata);
  566. };
  567. Inputmask.unmask = function(value, options) {
  568. return Inputmask(options).unmaskedvalue(value);
  569. };
  570. Inputmask.isValid = function(value, options) {
  571. return Inputmask(options).isValid(value);
  572. };
  573. Inputmask.remove = function(elems) {
  574. if (typeof elems === "string") {
  575. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  576. }
  577. elems = elems.nodeName ? [ elems ] : elems;
  578. $.each(elems, function(ndx, el) {
  579. if (el.inputmask) el.inputmask.remove();
  580. });
  581. };
  582. Inputmask.setValue = function(elems, value) {
  583. if (typeof elems === "string") {
  584. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  585. }
  586. elems = elems.nodeName ? [ elems ] : elems;
  587. $.each(elems, function(ndx, el) {
  588. if (el.inputmask) el.inputmask.setValue(value); else $(el).trigger("setvalue", [ value ]);
  589. });
  590. };
  591. Inputmask.escapeRegex = function(str) {
  592. var specials = [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ];
  593. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  594. };
  595. Inputmask.keyCode = {
  596. BACKSPACE: 8,
  597. BACKSPACE_SAFARI: 127,
  598. DELETE: 46,
  599. DOWN: 40,
  600. END: 35,
  601. ENTER: 13,
  602. ESCAPE: 27,
  603. HOME: 36,
  604. INSERT: 45,
  605. LEFT: 37,
  606. PAGE_DOWN: 34,
  607. PAGE_UP: 33,
  608. RIGHT: 39,
  609. SPACE: 32,
  610. TAB: 9,
  611. UP: 38,
  612. X: 88,
  613. CONTROL: 17
  614. };
  615. Inputmask.dependencyLib = $;
  616. function resolveAlias(aliasStr, options, opts) {
  617. var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
  618. if (aliasDefinition) {
  619. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts);
  620. $.extend(true, opts, aliasDefinition);
  621. $.extend(true, opts, options);
  622. return true;
  623. } else if (opts.mask === null) {
  624. opts.mask = aliasStr;
  625. }
  626. return false;
  627. }
  628. function generateMaskSet(opts, nocache) {
  629. function generateMask(mask, metadata, opts) {
  630. var regexMask = false;
  631. if (mask === null || mask === "") {
  632. regexMask = opts.regex !== null;
  633. if (regexMask) {
  634. mask = opts.regex;
  635. mask = mask.replace(/^(\^)(.*)(\$)$/, "$2");
  636. } else {
  637. regexMask = true;
  638. mask = ".*";
  639. }
  640. }
  641. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  642. opts.placeholder = "";
  643. }
  644. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  645. var repeatStart = opts.repeat === "*" ? 0 : opts.repeat === "+" ? 1 : opts.repeat;
  646. mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
  647. }
  648. var masksetDefinition, maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask;
  649. if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) {
  650. masksetDefinition = {
  651. mask: mask,
  652. maskToken: Inputmask.prototype.analyseMask(mask, regexMask, opts),
  653. validPositions: {},
  654. _buffer: undefined,
  655. buffer: undefined,
  656. tests: {},
  657. excludes: {},
  658. metadata: metadata,
  659. maskLength: undefined,
  660. jitOffset: {}
  661. };
  662. if (nocache !== true) {
  663. Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition;
  664. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
  665. }
  666. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
  667. return masksetDefinition;
  668. }
  669. var ms;
  670. if ($.isFunction(opts.mask)) {
  671. opts.mask = opts.mask(opts);
  672. }
  673. if ($.isArray(opts.mask)) {
  674. if (opts.mask.length > 1) {
  675. if (opts.keepStatic === null) {
  676. opts.keepStatic = "auto";
  677. for (var i = 0; i < opts.mask.length; i++) {
  678. if (opts.mask[i].charAt(0) !== opts.mask[0].charAt(0)) {
  679. opts.keepStatic = true;
  680. break;
  681. }
  682. }
  683. }
  684. var altMask = opts.groupmarker[0];
  685. $.each(opts.isRTL ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
  686. if (altMask.length > 1) {
  687. altMask += opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0];
  688. }
  689. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  690. altMask += msk.mask;
  691. } else {
  692. altMask += msk;
  693. }
  694. });
  695. altMask += opts.groupmarker[1];
  696. return generateMask(altMask, opts.mask, opts);
  697. } else opts.mask = opts.mask.pop();
  698. }
  699. if (opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  700. ms = generateMask(opts.mask.mask, opts.mask, opts);
  701. } else {
  702. ms = generateMask(opts.mask, opts.mask, opts);
  703. }
  704. return ms;
  705. }
  706. function isInputEventSupported(eventName) {
  707. var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el;
  708. if (!isSupported) {
  709. el.setAttribute(evName, "return;");
  710. isSupported = typeof el[evName] === "function";
  711. }
  712. el = null;
  713. return isSupported;
  714. }
  715. function maskScope(actionObj, maskset, opts) {
  716. maskset = maskset || this.maskset;
  717. opts = opts || this.opts;
  718. var inputmask = this, el = this.el, isRTL = this.isRTL, undoValue, $el, skipKeyPressEvent = false, skipInputEvent = false, ignorable = false, maxLength, mouseEnter = false, colorMask, originalPlaceholder;
  719. function getMaskTemplate(baseOnInput, minimalPos, includeMode, noJit, clearOptionalTail) {
  720. var greedy = opts.greedy;
  721. if (clearOptionalTail) opts.greedy = false;
  722. minimalPos = minimalPos || 0;
  723. var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos, lvp = getLastValidPosition();
  724. do {
  725. if (baseOnInput === true && getMaskSet().validPositions[pos]) {
  726. 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];
  727. test = testPos.match;
  728. ndxIntlzr = testPos.locator.slice();
  729. maskTemplate.push(includeMode === true ? testPos.input : includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  730. } else {
  731. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  732. test = testPos.match;
  733. ndxIntlzr = testPos.locator.slice();
  734. var jitMasking = noJit === true ? false : opts.jitMasking !== false ? opts.jitMasking : test.jit;
  735. if (jitMasking === false || jitMasking === undefined || typeof jitMasking === "number" && isFinite(jitMasking) && jitMasking > pos) {
  736. maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  737. }
  738. }
  739. if (opts.keepStatic === "auto") {
  740. if (test.newBlockMarker && test.fn !== null) {
  741. opts.keepStatic = pos - 1;
  742. }
  743. }
  744. pos++;
  745. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || minimalPos > pos);
  746. if (maskTemplate[maskTemplate.length - 1] === "") {
  747. maskTemplate.pop();
  748. }
  749. if (includeMode !== false || getMaskSet().maskLength === undefined) getMaskSet().maskLength = pos - 1;
  750. opts.greedy = greedy;
  751. return maskTemplate;
  752. }
  753. function getMaskSet() {
  754. return maskset;
  755. }
  756. function resetMaskSet(soft) {
  757. var maskset = getMaskSet();
  758. maskset.buffer = undefined;
  759. if (soft !== true) {
  760. maskset.validPositions = {};
  761. maskset.p = 0;
  762. }
  763. }
  764. function getLastValidPosition(closestTo, strict, validPositions) {
  765. var before = -1, after = -1, valids = validPositions || getMaskSet().validPositions;
  766. if (closestTo === undefined) closestTo = -1;
  767. for (var posNdx in valids) {
  768. var psNdx = parseInt(posNdx);
  769. if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
  770. if (psNdx <= closestTo) before = psNdx;
  771. if (psNdx >= closestTo) after = psNdx;
  772. }
  773. }
  774. return before === -1 || before == closestTo ? after : after == -1 ? before : closestTo - before < after - closestTo ? before : after;
  775. }
  776. function getDecisionTaker(tst) {
  777. var decisionTaker = tst.locator[tst.alternation];
  778. if (typeof decisionTaker == "string" && decisionTaker.length > 0) {
  779. decisionTaker = decisionTaker.split(",")[0];
  780. }
  781. return decisionTaker !== undefined ? decisionTaker.toString() : "";
  782. }
  783. function getLocator(tst, align) {
  784. var locator = (tst.alternation != undefined ? tst.mloc[getDecisionTaker(tst)] : tst.locator).join("");
  785. if (locator !== "") while (locator.length < align) locator += "0";
  786. return locator;
  787. }
  788. function determineTestTemplate(pos, tests) {
  789. pos = pos > 0 ? pos - 1 : 0;
  790. var altTest = getTest(pos), targetLocator = getLocator(altTest), tstLocator, closest, bestMatch;
  791. for (var ndx = 0; ndx < tests.length; ndx++) {
  792. var tst = tests[ndx];
  793. tstLocator = getLocator(tst, targetLocator.length);
  794. var distance = Math.abs(tstLocator - targetLocator);
  795. 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) {
  796. closest = distance;
  797. bestMatch = tst;
  798. }
  799. }
  800. return bestMatch;
  801. }
  802. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  803. return getMaskSet().validPositions[pos] || determineTestTemplate(pos, getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
  804. }
  805. function getTest(pos, tests) {
  806. if (getMaskSet().validPositions[pos]) {
  807. return getMaskSet().validPositions[pos];
  808. }
  809. return (tests || getTests(pos))[0];
  810. }
  811. function positionCanMatchDefinition(pos, def) {
  812. var valid = false, tests = getTests(pos);
  813. for (var tndx = 0; tndx < tests.length; tndx++) {
  814. if (tests[tndx].match && tests[tndx].match.def === def) {
  815. valid = true;
  816. break;
  817. }
  818. }
  819. return valid;
  820. }
  821. function getTests(pos, ndxIntlzr, tstPs) {
  822. var maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [ 0 ], matches = [], insertStop = false, latestMatch, cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "";
  823. function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) {
  824. function handleMatch(match, loopNdx, quantifierRecurse) {
  825. function isFirstMatch(latestMatch, tokenGroup) {
  826. var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  827. if (!firstMatch) {
  828. $.each(tokenGroup.matches, function(ndx, match) {
  829. if (match.isQuantifier === true) firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]); else if (match.hasOwnProperty("matches")) firstMatch = isFirstMatch(latestMatch, match);
  830. if (firstMatch) return false;
  831. });
  832. }
  833. return firstMatch;
  834. }
  835. function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
  836. var bestMatch, indexPos;
  837. if (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) {
  838. $.each(getMaskSet().tests[pos] || [ getMaskSet().validPositions[pos] ], function(ndx, lmnt) {
  839. if (lmnt.mloc[alternateNdx]) {
  840. bestMatch = lmnt;
  841. return false;
  842. }
  843. var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation, ndxPos = lmnt.locator[alternation] !== undefined ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
  844. if ((indexPos === undefined || ndxPos < indexPos) && ndxPos !== -1) {
  845. bestMatch = lmnt;
  846. indexPos = ndxPos;
  847. }
  848. });
  849. }
  850. if (bestMatch) {
  851. var bestMatchAltIndex = bestMatch.locator[bestMatch.alternation];
  852. var locator = bestMatch.mloc[alternateNdx] || bestMatch.mloc[bestMatchAltIndex] || bestMatch.locator;
  853. return locator.slice((targetAlternation !== undefined ? targetAlternation : bestMatch.alternation) + 1);
  854. } else {
  855. return targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
  856. }
  857. }
  858. function isSubsetOf(source, target) {
  859. function expand(pattern) {
  860. var expanded = [], start, end;
  861. for (var i = 0, l = pattern.length; i < l; i++) {
  862. if (pattern.charAt(i) === "-") {
  863. end = pattern.charCodeAt(i + 1);
  864. while (++start < end) expanded.push(String.fromCharCode(start));
  865. } else {
  866. start = pattern.charCodeAt(i);
  867. expanded.push(pattern.charAt(i));
  868. }
  869. }
  870. return expanded.join("");
  871. }
  872. if (opts.regex && source.match.fn !== null && target.match.fn !== null) {
  873. return expand(target.match.def.replace(/[\[\]]/g, "")).indexOf(expand(source.match.def.replace(/[\[\]]/g, ""))) !== -1;
  874. }
  875. return source.match.def === target.match.nativeDef;
  876. }
  877. function staticCanMatchDefinition(source, target) {
  878. var sloc = source.locator.slice(source.alternation).join(""), tloc = target.locator.slice(target.alternation).join(""), canMatch = sloc == tloc;
  879. canMatch = canMatch && source.match.fn === null && target.match.fn !== null ? target.match.fn.test(source.match.def, getMaskSet(), pos, false, opts, false) : false;
  880. return canMatch;
  881. }
  882. function setMergeLocators(targetMatch, altMatch) {
  883. if (altMatch === undefined || targetMatch.alternation === altMatch.alternation && targetMatch.locator[targetMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
  884. targetMatch.mloc = targetMatch.mloc || {};
  885. var locNdx = targetMatch.locator[targetMatch.alternation];
  886. if (locNdx === undefined) targetMatch.alternation = undefined; else {
  887. if (typeof locNdx === "string") locNdx = locNdx.split(",")[0];
  888. if (targetMatch.mloc[locNdx] === undefined) targetMatch.mloc[locNdx] = targetMatch.locator.slice();
  889. if (altMatch !== undefined) {
  890. for (var ndx in altMatch.mloc) {
  891. if (typeof ndx === "string") ndx = ndx.split(",")[0];
  892. if (targetMatch.mloc[ndx] === undefined) targetMatch.mloc[ndx] = altMatch.mloc[ndx];
  893. }
  894. targetMatch.locator[targetMatch.alternation] = Object.keys(targetMatch.mloc).join(",");
  895. }
  896. return true;
  897. }
  898. }
  899. return false;
  900. }
  901. if (testPos > 500 && quantifierRecurse !== undefined) {
  902. 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;
  903. }
  904. if (testPos === pos && match.matches === undefined) {
  905. matches.push({
  906. match: match,
  907. locator: loopNdx.reverse(),
  908. cd: cacheDependency,
  909. mloc: {}
  910. });
  911. return true;
  912. } else if (match.matches !== undefined) {
  913. if (match.isGroup && quantifierRecurse !== match) {
  914. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx, quantifierRecurse);
  915. if (match) return true;
  916. } else if (match.isOptional) {
  917. var optionalToken = match;
  918. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  919. if (match) {
  920. $.each(matches, function(ndx, mtch) {
  921. mtch.match.optionality = true;
  922. });
  923. latestMatch = matches[matches.length - 1].match;
  924. if (quantifierRecurse === undefined && isFirstMatch(latestMatch, optionalToken)) {
  925. insertStop = true;
  926. testPos = pos;
  927. } else return true;
  928. }
  929. } else if (match.isAlternator) {
  930. var alternateToken = match, malternateMatches = [], maltMatches, currentMatches = matches.slice(), loopNdxCnt = loopNdx.length;
  931. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  932. if (altIndex === -1 || typeof altIndex === "string") {
  933. var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr = [], amndx;
  934. if (typeof altIndex == "string") {
  935. altIndexArr = altIndex.split(",");
  936. } else {
  937. for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  938. altIndexArr.push(amndx.toString());
  939. }
  940. }
  941. if (getMaskSet().excludes[pos]) {
  942. var altIndexArrClone = altIndexArr.slice();
  943. for (var i = 0, el = getMaskSet().excludes[pos].length; i < el; i++) {
  944. altIndexArr.splice(altIndexArr.indexOf(getMaskSet().excludes[pos][i].toString()), 1);
  945. }
  946. if (altIndexArr.length === 0) {
  947. getMaskSet().excludes[pos] = undefined;
  948. altIndexArr = altIndexArrClone;
  949. }
  950. }
  951. if (opts.keepStatic === true || isFinite(parseInt(opts.keepStatic)) && currentPos >= opts.keepStatic) altIndexArr = altIndexArr.slice(0, 1);
  952. var unMatchedAlternation = false;
  953. for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
  954. amndx = parseInt(altIndexArr[ndx]);
  955. matches = [];
  956. ndxInitializer = typeof altIndex === "string" ? resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice() : ndxInitializerClone.slice();
  957. if (alternateToken.matches[amndx] && handleMatch(alternateToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse)) match = true; else if (ndx === 0) {
  958. unMatchedAlternation = true;
  959. }
  960. maltMatches = matches.slice();
  961. testPos = currentPos;
  962. matches = [];
  963. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  964. var altMatch = maltMatches[ndx1], dropMatch = false;
  965. altMatch.match.jit = altMatch.match.jit || unMatchedAlternation;
  966. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  967. setMergeLocators(altMatch);
  968. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  969. var altMatch2 = malternateMatches[ndx2];
  970. if (typeof altIndex !== "string" || altMatch.alternation !== undefined && $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
  971. if (altMatch.match.nativeDef === altMatch2.match.nativeDef) {
  972. dropMatch = true;
  973. setMergeLocators(altMatch2, altMatch);
  974. break;
  975. } else if (isSubsetOf(altMatch, altMatch2)) {
  976. if (setMergeLocators(altMatch, altMatch2)) {
  977. dropMatch = true;
  978. malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
  979. }
  980. break;
  981. } else if (isSubsetOf(altMatch2, altMatch)) {
  982. setMergeLocators(altMatch2, altMatch);
  983. break;
  984. } else if (staticCanMatchDefinition(altMatch, altMatch2)) {
  985. if (setMergeLocators(altMatch, altMatch2)) {
  986. dropMatch = true;
  987. malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
  988. }
  989. break;
  990. }
  991. }
  992. }
  993. if (!dropMatch) {
  994. malternateMatches.push(altMatch);
  995. }
  996. }
  997. }
  998. matches = currentMatches.concat(malternateMatches);
  999. testPos = pos;
  1000. insertStop = matches.length > 0;
  1001. match = malternateMatches.length > 0;
  1002. ndxInitializer = ndxInitializerClone.slice();
  1003. } else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse);
  1004. if (match) return true;
  1005. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  1006. var qt = match;
  1007. for (var qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && testPos <= pos; qndx++) {
  1008. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  1009. match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), tokenGroup);
  1010. if (match) {
  1011. latestMatch = matches[matches.length - 1].match;
  1012. latestMatch.optionalQuantifier = qndx >= qt.quantifier.min;
  1013. latestMatch.jit = (qndx || 1) * tokenGroup.matches.indexOf(latestMatch) >= qt.quantifier.jit;
  1014. if (latestMatch.optionalQuantifier && isFirstMatch(latestMatch, tokenGroup)) {
  1015. insertStop = true;
  1016. testPos = pos;
  1017. break;
  1018. }
  1019. if (latestMatch.jit) {
  1020. getMaskSet().jitOffset[pos] = tokenGroup.matches.indexOf(latestMatch);
  1021. }
  1022. return true;
  1023. }
  1024. }
  1025. } else {
  1026. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  1027. if (match) return true;
  1028. }
  1029. } else {
  1030. testPos++;
  1031. }
  1032. }
  1033. for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) {
  1034. if (maskToken.matches[tndx].isQuantifier !== true) {
  1035. var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse);
  1036. if (match && testPos === pos) {
  1037. return match;
  1038. } else if (testPos > pos) {
  1039. break;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. function mergeLocators(pos, tests) {
  1045. var locator = [];
  1046. if (!$.isArray(tests)) tests = [ tests ];
  1047. if (tests.length > 0) {
  1048. if (tests[0].alternation === undefined) {
  1049. locator = determineTestTemplate(pos, tests.slice()).locator.slice();
  1050. if (locator.length === 0) locator = tests[0].locator.slice();
  1051. } else {
  1052. $.each(tests, function(ndx, tst) {
  1053. if (tst.def !== "") {
  1054. if (locator.length === 0) locator = tst.locator.slice(); else {
  1055. for (var i = 0; i < locator.length; i++) {
  1056. if (tst.locator[i] && locator[i].toString().indexOf(tst.locator[i]) === -1) {
  1057. locator[i] += "," + tst.locator[i];
  1058. }
  1059. }
  1060. }
  1061. }
  1062. });
  1063. }
  1064. }
  1065. return locator;
  1066. }
  1067. if (pos > -1) {
  1068. if (ndxIntlzr === undefined) {
  1069. var previousPos = pos - 1, test;
  1070. while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
  1071. previousPos--;
  1072. }
  1073. if (test !== undefined && previousPos > -1) {
  1074. ndxInitializer = mergeLocators(previousPos, test);
  1075. cacheDependency = ndxInitializer.join("");
  1076. testPos = previousPos;
  1077. }
  1078. }
  1079. if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) {
  1080. return getMaskSet().tests[pos];
  1081. }
  1082. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1083. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]);
  1084. if (match && testPos === pos || testPos > pos) {
  1085. break;
  1086. }
  1087. }
  1088. }
  1089. if (matches.length === 0 || insertStop) {
  1090. matches.push({
  1091. match: {
  1092. fn: null,
  1093. optionality: false,
  1094. casing: null,
  1095. def: "",
  1096. placeholder: ""
  1097. },
  1098. locator: [],
  1099. mloc: {},
  1100. cd: cacheDependency
  1101. });
  1102. }
  1103. if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) {
  1104. return $.extend(true, [], matches);
  1105. }
  1106. getMaskSet().tests[pos] = $.extend(true, [], matches);
  1107. return getMaskSet().tests[pos];
  1108. }
  1109. function getBufferTemplate() {
  1110. if (getMaskSet()._buffer === undefined) {
  1111. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1112. if (getMaskSet().buffer === undefined) getMaskSet().buffer = getMaskSet()._buffer.slice();
  1113. }
  1114. return getMaskSet()._buffer;
  1115. }
  1116. function getBuffer(noCache) {
  1117. if (getMaskSet().buffer === undefined || noCache === true) {
  1118. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1119. if (getMaskSet()._buffer === undefined) getMaskSet()._buffer = getMaskSet().buffer.slice();
  1120. }
  1121. return getMaskSet().buffer;
  1122. }
  1123. function refreshFromBuffer(start, end, buffer) {
  1124. var i, p;
  1125. if (start === true) {
  1126. resetMaskSet();
  1127. start = 0;
  1128. end = buffer.length;
  1129. } else {
  1130. for (i = start; i < end; i++) {
  1131. delete getMaskSet().validPositions[i];
  1132. }
  1133. }
  1134. p = start;
  1135. for (i = start; i < end; i++) {
  1136. resetMaskSet(true);
  1137. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1138. var valResult = isValid(p, buffer[i], true, true);
  1139. if (valResult !== false) {
  1140. resetMaskSet(true);
  1141. p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. function casing(elem, test, pos) {
  1147. switch (opts.casing || test.casing) {
  1148. case "upper":
  1149. elem = elem.toUpperCase();
  1150. break;
  1151. case "lower":
  1152. elem = elem.toLowerCase();
  1153. break;
  1154. case "title":
  1155. var posBefore = getMaskSet().validPositions[pos - 1];
  1156. if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
  1157. elem = elem.toUpperCase();
  1158. } else {
  1159. elem = elem.toLowerCase();
  1160. }
  1161. break;
  1162. default:
  1163. if ($.isFunction(opts.casing)) {
  1164. var args = Array.prototype.slice.call(arguments);
  1165. args.push(getMaskSet().validPositions);
  1166. elem = opts.casing.apply(this, args);
  1167. }
  1168. }
  1169. return elem;
  1170. }
  1171. function checkAlternationMatch(altArr1, altArr2, na) {
  1172. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = false, naArr = na !== undefined ? na.split(",") : [], naNdx;
  1173. for (var i = 0; i < naArr.length; i++) {
  1174. if ((naNdx = altArr1.indexOf(naArr[i])) !== -1) {
  1175. altArr1.splice(naNdx, 1);
  1176. }
  1177. }
  1178. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1179. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1180. isMatch = true;
  1181. break;
  1182. }
  1183. }
  1184. return isMatch;
  1185. }
  1186. function alternate(pos, c, strict, fromSetValid, rAltPos) {
  1187. var validPsClone = $.extend(true, {}, getMaskSet().validPositions), lastAlt, alternation, isValidRslt = false, altPos, prevAltPos, i, validPos, decisionPos, lAltPos = rAltPos !== undefined ? rAltPos : getLastValidPosition();
  1188. if (lAltPos === -1 && rAltPos === undefined) {
  1189. lastAlt = 0;
  1190. prevAltPos = getTest(lastAlt);
  1191. alternation = prevAltPos.alternation;
  1192. } else {
  1193. for (;lAltPos >= 0; lAltPos--) {
  1194. altPos = getMaskSet().validPositions[lAltPos];
  1195. if (altPos && altPos.alternation !== undefined) {
  1196. if (prevAltPos && prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1197. break;
  1198. }
  1199. lastAlt = lAltPos;
  1200. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1201. prevAltPos = altPos;
  1202. }
  1203. }
  1204. }
  1205. if (alternation !== undefined) {
  1206. decisionPos = parseInt(lastAlt);
  1207. getMaskSet().excludes[decisionPos] = getMaskSet().excludes[decisionPos] || [];
  1208. if (pos !== true) {
  1209. getMaskSet().excludes[decisionPos].push(getDecisionTaker(prevAltPos));
  1210. }
  1211. var validInputsClone = [], staticInputsBeforePos = 0;
  1212. for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) {
  1213. validPos = getMaskSet().validPositions[i];
  1214. if (validPos && validPos.generatedInput !== true) {
  1215. validInputsClone.push(validPos.input);
  1216. } else if (i < pos) staticInputsBeforePos++;
  1217. delete getMaskSet().validPositions[i];
  1218. }
  1219. while (getMaskSet().excludes[decisionPos] && getMaskSet().excludes[decisionPos].length < 10) {
  1220. var posOffset = staticInputsBeforePos * -1, validInputs = validInputsClone.slice();
  1221. getMaskSet().tests[decisionPos] = undefined;
  1222. resetMaskSet(true);
  1223. isValidRslt = true;
  1224. while (validInputs.length > 0) {
  1225. var input = validInputs.shift();
  1226. if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
  1227. break;
  1228. }
  1229. }
  1230. if (isValidRslt && c !== undefined) {
  1231. var targetLvp = getLastValidPosition(pos) + 1;
  1232. for (i = decisionPos; i < getLastValidPosition() + 1; i++) {
  1233. validPos = getMaskSet().validPositions[i];
  1234. if ((validPos === undefined || validPos.match.fn == null) && i < pos + posOffset) {
  1235. posOffset++;
  1236. }
  1237. }
  1238. pos = pos + posOffset;
  1239. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
  1240. }
  1241. if (!isValidRslt) {
  1242. resetMaskSet();
  1243. prevAltPos = getTest(decisionPos);
  1244. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1245. if (getMaskSet().excludes[decisionPos]) {
  1246. var decisionTaker = getDecisionTaker(prevAltPos);
  1247. if (getMaskSet().excludes[decisionPos].indexOf(decisionTaker) !== -1) {
  1248. isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
  1249. break;
  1250. }
  1251. getMaskSet().excludes[decisionPos].push(decisionTaker);
  1252. for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) delete getMaskSet().validPositions[i];
  1253. } else {
  1254. isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
  1255. break;
  1256. }
  1257. } else break;
  1258. }
  1259. }
  1260. getMaskSet().excludes[decisionPos] = undefined;
  1261. return isValidRslt;
  1262. }
  1263. function isValid(pos, c, strict, fromSetValid, fromAlternate, validateOnly) {
  1264. function isSelection(posObj) {
  1265. return isRTL ? posObj.begin - posObj.end > 1 || posObj.begin - posObj.end === 1 : posObj.end - posObj.begin > 1 || posObj.end - posObj.begin === 1;
  1266. }
  1267. strict = strict === true;
  1268. var maskPos = pos;
  1269. if (pos.begin !== undefined) {
  1270. maskPos = isRTL ? pos.end : pos.begin;
  1271. }
  1272. function _isValid(position, c, strict) {
  1273. var rslt = false;
  1274. $.each(getTests(position), function(ndx, tst) {
  1275. var test = tst.match;
  1276. getBuffer(true);
  1277. rslt = test.fn != null ? test.fn.test(c, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? {
  1278. c: getPlaceholder(position, test, true) || test.def,
  1279. pos: position
  1280. } : false;
  1281. if (rslt !== false) {
  1282. var elem = rslt.c !== undefined ? rslt.c : c, validatedPos = position;
  1283. elem = elem === opts.skipOptionalPartCharacter && test.fn === null ? getPlaceholder(position, test, true) || test.def : elem;
  1284. if (rslt.remove !== undefined) {
  1285. if (!$.isArray(rslt.remove)) rslt.remove = [ rslt.remove ];
  1286. $.each(rslt.remove.sort(function(a, b) {
  1287. return b - a;
  1288. }), function(ndx, lmnt) {
  1289. revalidateMask({
  1290. begin: lmnt,
  1291. end: lmnt + 1
  1292. });
  1293. });
  1294. }
  1295. if (rslt.insert !== undefined) {
  1296. if (!$.isArray(rslt.insert)) rslt.insert = [ rslt.insert ];
  1297. $.each(rslt.insert.sort(function(a, b) {
  1298. return a - b;
  1299. }), function(ndx, lmnt) {
  1300. isValid(lmnt.pos, lmnt.c, true, fromSetValid);
  1301. });
  1302. }
  1303. if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) {
  1304. validatedPos = rslt.pos;
  1305. }
  1306. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1307. return false;
  1308. }
  1309. if (!revalidateMask(pos, $.extend({}, tst, {
  1310. input: casing(elem, test, validatedPos)
  1311. }), fromSetValid, validatedPos)) {
  1312. rslt = false;
  1313. }
  1314. return false;
  1315. }
  1316. });
  1317. return rslt;
  1318. }
  1319. var result = true, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
  1320. if ($.isFunction(opts.preValidation) && !strict && fromSetValid !== true && validateOnly !== true) {
  1321. result = opts.preValidation(getBuffer(), maskPos, c, isSelection(pos), opts, getMaskSet());
  1322. }
  1323. if (result === true) {
  1324. trackbackPositions(undefined, maskPos, true);
  1325. if (maxLength === undefined || maskPos < maxLength) {
  1326. result = _isValid(maskPos, c, strict);
  1327. if ((!strict || fromSetValid === true) && result === false && validateOnly !== true) {
  1328. var currentPosValid = getMaskSet().validPositions[maskPos];
  1329. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1330. result = {
  1331. caret: seekNext(maskPos)
  1332. };
  1333. } else {
  1334. if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && (!isMask(maskPos, true) || getMaskSet().jitOffset[maskPos])) {
  1335. if (getMaskSet().jitOffset[maskPos] && getMaskSet().validPositions[seekNext(maskPos)] === undefined) {
  1336. result = isValid(maskPos + getMaskSet().jitOffset[maskPos], c, strict);
  1337. if (result !== false) result.caret = maskPos;
  1338. } else for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1339. result = _isValid(nPos, c, strict);
  1340. if (result !== false) {
  1341. result = trackbackPositions(maskPos, result.pos !== undefined ? result.pos : nPos) || result;
  1342. maskPos = nPos;
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. }
  1348. }
  1349. }
  1350. if (result === false && opts.keepStatic !== false && (opts.regex == null || isComplete(getBuffer())) && !strict && fromAlternate !== true) {
  1351. result = alternate(maskPos, c, strict, fromSetValid);
  1352. }
  1353. if (result === true) {
  1354. result = {
  1355. pos: maskPos
  1356. };
  1357. }
  1358. }
  1359. if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true && validateOnly !== true) {
  1360. var postResult = opts.postValidation(getBuffer(true), pos.begin !== undefined ? isRTL ? pos.end : pos.begin : pos, result, opts);
  1361. if (postResult !== undefined) {
  1362. if (postResult.refreshFromBuffer && postResult.buffer) {
  1363. var refresh = postResult.refreshFromBuffer;
  1364. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postResult.buffer);
  1365. }
  1366. result = postResult === true ? result : postResult;
  1367. }
  1368. }
  1369. if (result && result.pos === undefined) {
  1370. result.pos = maskPos;
  1371. }
  1372. if (result === false || validateOnly === true) {
  1373. resetMaskSet(true);
  1374. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1375. }
  1376. return result;
  1377. }
  1378. function trackbackPositions(originalPos, newPos, fillOnly) {
  1379. var result;
  1380. if (originalPos === undefined) {
  1381. for (originalPos = newPos - 1; originalPos > 0; originalPos--) {
  1382. if (getMaskSet().validPositions[originalPos]) break;
  1383. }
  1384. }
  1385. for (var ps = originalPos; ps < newPos; ps++) {
  1386. if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
  1387. var vp = ps == 0 ? getTest(ps) : getMaskSet().validPositions[ps - 1];
  1388. if (vp) {
  1389. var tests = getTests(ps).slice();
  1390. if (tests[tests.length - 1].match.def === "") tests.pop();
  1391. var bestMatch = determineTestTemplate(ps, tests);
  1392. bestMatch = $.extend({}, bestMatch, {
  1393. input: getPlaceholder(ps, bestMatch.match, true) || bestMatch.match.def
  1394. });
  1395. bestMatch.generatedInput = true;
  1396. revalidateMask(ps, bestMatch, true);
  1397. if (fillOnly !== true) {
  1398. var cvpInput = getMaskSet().validPositions[newPos].input;
  1399. getMaskSet().validPositions[newPos] = undefined;
  1400. result = isValid(newPos, cvpInput, true, true);
  1401. }
  1402. }
  1403. }
  1404. }
  1405. return result;
  1406. }
  1407. function revalidateMask(pos, validTest, fromSetValid, validatedPos) {
  1408. function IsEnclosedStatic(pos, valids, selection) {
  1409. var posMatch = valids[pos];
  1410. if (posMatch !== undefined && (posMatch.match.fn === null && posMatch.match.optionality !== true || posMatch.input === opts.radixPoint)) {
  1411. 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];
  1412. return prevMatch && nextMatch;
  1413. }
  1414. return false;
  1415. }
  1416. var begin = pos.begin !== undefined ? pos.begin : pos, end = pos.end !== undefined ? pos.end : pos;
  1417. if (pos.begin > pos.end) {
  1418. begin = pos.end;
  1419. end = pos.begin;
  1420. }
  1421. validatedPos = validatedPos !== undefined ? validatedPos : begin;
  1422. if (begin !== end || opts.insertMode && getMaskSet().validPositions[validatedPos] !== undefined && fromSetValid === undefined) {
  1423. var positionsClone = $.extend(true, {}, getMaskSet().validPositions), lvp = getLastValidPosition(undefined, true), i;
  1424. getMaskSet().p = begin;
  1425. for (i = lvp; i >= begin; i--) {
  1426. if (getMaskSet().validPositions[i] && getMaskSet().validPositions[i].match.nativeDef === "+") {
  1427. opts.isNegative = false;
  1428. }
  1429. delete getMaskSet().validPositions[i];
  1430. }
  1431. var valid = true, j = validatedPos, vps = getMaskSet().validPositions, needsValidation = false, posMatch = j, i = j;
  1432. if (validTest) {
  1433. getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
  1434. posMatch++;
  1435. j++;
  1436. if (begin < end) i++;
  1437. }
  1438. for (;i <= lvp; i++) {
  1439. var t = positionsClone[i];
  1440. if (t !== undefined && (i >= end || i >= begin && t.generatedInput !== true && IsEnclosedStatic(i, positionsClone, {
  1441. begin: begin,
  1442. end: end
  1443. }))) {
  1444. while (getTest(posMatch).match.def !== "") {
  1445. if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.nativeDef === t.match.nativeDef) {
  1446. getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
  1447. getMaskSet().validPositions[posMatch].input = t.input;
  1448. trackbackPositions(undefined, posMatch, true);
  1449. j = posMatch + 1;
  1450. valid = true;
  1451. } else if (opts.shiftPositions && positionCanMatchDefinition(posMatch, t.match.def)) {
  1452. var result = isValid(posMatch, t.input, true, true);
  1453. valid = result !== false;
  1454. j = result.caret || result.insert ? getLastValidPosition() : posMatch + 1;
  1455. needsValidation = true;
  1456. } else {
  1457. valid = t.generatedInput === true || t.input === opts.radixPoint && opts.numericInput === true;
  1458. }
  1459. if (valid) break;
  1460. if (!valid && posMatch > end && isMask(posMatch, true) && (t.match.fn !== null || posMatch > getMaskSet().maskLength)) {
  1461. break;
  1462. }
  1463. posMatch++;
  1464. }
  1465. if (getTest(posMatch).match.def == "") valid = false;
  1466. posMatch = j;
  1467. }
  1468. if (!valid) break;
  1469. }
  1470. if (!valid) {
  1471. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1472. resetMaskSet(true);
  1473. return false;
  1474. }
  1475. } else if (validTest) {
  1476. getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
  1477. }
  1478. resetMaskSet(true);
  1479. return true;
  1480. }
  1481. function isMask(pos, strict) {
  1482. var test = getTestTemplate(pos).match;
  1483. if (test.def === "") test = getTest(pos).match;
  1484. if (test.fn != null) {
  1485. return test.fn;
  1486. }
  1487. if (strict !== true && pos > -1) {
  1488. var tests = getTests(pos);
  1489. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1490. }
  1491. return false;
  1492. }
  1493. function seekNext(pos, newBlock) {
  1494. var position = pos + 1;
  1495. while (getTest(position).match.def !== "" && (newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position)) || newBlock !== true && !isMask(position))) {
  1496. position++;
  1497. }
  1498. return position;
  1499. }
  1500. function seekPrevious(pos, newBlock) {
  1501. var position = pos, tests;
  1502. if (position <= 0) return 0;
  1503. while (--position > 0 && (newBlock === true && getTest(position).match.newBlockMarker !== true || newBlock !== true && !isMask(position) && (tests = getTests(position),
  1504. tests.length < 2 || tests.length === 2 && tests[1].match.def === ""))) {}
  1505. return position;
  1506. }
  1507. function writeBuffer(input, buffer, caretPos, event, triggerEvents) {
  1508. if (event && $.isFunction(opts.onBeforeWrite)) {
  1509. var result = opts.onBeforeWrite.call(inputmask, event, buffer, caretPos, opts);
  1510. if (result) {
  1511. if (result.refreshFromBuffer) {
  1512. var refresh = result.refreshFromBuffer;
  1513. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1514. buffer = getBuffer(true);
  1515. }
  1516. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1517. }
  1518. }
  1519. if (input !== undefined) {
  1520. input.inputmask._valueSet(buffer.join(""));
  1521. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1522. caret(input, caretPos);
  1523. } else renderColorMask(input, caretPos, buffer.length === 0);
  1524. if (triggerEvents === true) {
  1525. var $input = $(input), nptVal = input.inputmask._valueGet();
  1526. skipInputEvent = true;
  1527. $input.trigger("input");
  1528. setTimeout(function() {
  1529. if (nptVal === getBufferTemplate().join("")) {
  1530. $input.trigger("cleared");
  1531. } else if (isComplete(buffer) === true) {
  1532. $input.trigger("complete");
  1533. }
  1534. }, 0);
  1535. }
  1536. }
  1537. }
  1538. function getPlaceholder(pos, test, returnPL) {
  1539. test = test || getTest(pos).match;
  1540. if (test.placeholder !== undefined || returnPL === true) {
  1541. return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
  1542. } else if (test.fn === null) {
  1543. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1544. var tests = getTests(pos), staticAlternations = [], prevTest;
  1545. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1546. for (var i = 0; i < tests.length; i++) {
  1547. 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))) {
  1548. staticAlternations.push(tests[i]);
  1549. if (tests[i].match.fn === null) prevTest = tests[i];
  1550. if (staticAlternations.length > 1) {
  1551. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1552. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1553. }
  1554. }
  1555. }
  1556. }
  1557. }
  1558. }
  1559. return test.def;
  1560. }
  1561. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1562. }
  1563. function HandleNativePlaceholder(npt, value) {
  1564. if (ie) {
  1565. if (npt.inputmask._valueGet() !== value) {
  1566. var buffer = getBuffer().slice(), nptValue = npt.inputmask._valueGet();
  1567. if (nptValue !== value) {
  1568. var lvp = getLastValidPosition();
  1569. if (lvp === -1 && nptValue === getBufferTemplate().join("")) {
  1570. buffer = [];
  1571. } else if (lvp !== -1) {
  1572. clearOptionalTail(buffer);
  1573. }
  1574. writeBuffer(npt, buffer);
  1575. }
  1576. }
  1577. } else if (npt.placeholder !== value) {
  1578. npt.placeholder = value;
  1579. if (npt.placeholder === "") npt.removeAttribute("placeholder");
  1580. }
  1581. }
  1582. var EventRuler = {
  1583. on: function(input, eventName, eventHandler) {
  1584. var ev = function(e) {
  1585. var that = this;
  1586. if (that.inputmask === undefined && this.nodeName !== "FORM") {
  1587. var imOpts = $.data(that, "_inputmask_opts");
  1588. if (imOpts) new Inputmask(imOpts).mask(that); else EventRuler.off(that);
  1589. } 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))) {
  1590. e.preventDefault();
  1591. } else {
  1592. switch (e.type) {
  1593. case "input":
  1594. if (skipInputEvent === true) {
  1595. skipInputEvent = false;
  1596. return e.preventDefault();
  1597. }
  1598. if (mobile) {
  1599. var args = arguments;
  1600. setTimeout(function() {
  1601. eventHandler.apply(that, args);
  1602. caret(that, that.inputmask.caretPos, undefined, true);
  1603. }, 0);
  1604. return false;
  1605. }
  1606. break;
  1607. case "keydown":
  1608. skipKeyPressEvent = false;
  1609. skipInputEvent = false;
  1610. break;
  1611. case "keypress":
  1612. if (skipKeyPressEvent === true) {
  1613. return e.preventDefault();
  1614. }
  1615. skipKeyPressEvent = true;
  1616. break;
  1617. case "click":
  1618. if (iemobile || iphone) {
  1619. var args = arguments;
  1620. setTimeout(function() {
  1621. eventHandler.apply(that, args);
  1622. }, 0);
  1623. return false;
  1624. }
  1625. break;
  1626. }
  1627. var returnVal = eventHandler.apply(that, arguments);
  1628. if (returnVal === false) {
  1629. e.preventDefault();
  1630. e.stopPropagation();
  1631. }
  1632. return returnVal;
  1633. }
  1634. };
  1635. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1636. input.inputmask.events[eventName].push(ev);
  1637. if ($.inArray(eventName, [ "submit", "reset" ]) !== -1) {
  1638. if (input.form !== null) $(input.form).on(eventName, ev);
  1639. } else {
  1640. $(input).on(eventName, ev);
  1641. }
  1642. },
  1643. off: function(input, event) {
  1644. if (input.inputmask && input.inputmask.events) {
  1645. var events;
  1646. if (event) {
  1647. events = [];
  1648. events[event] = input.inputmask.events[event];
  1649. } else {
  1650. events = input.inputmask.events;
  1651. }
  1652. $.each(events, function(eventName, evArr) {
  1653. while (evArr.length > 0) {
  1654. var ev = evArr.pop();
  1655. if ($.inArray(eventName, [ "submit", "reset" ]) !== -1) {
  1656. if (input.form !== null) $(input.form).off(eventName, ev);
  1657. } else {
  1658. $(input).off(eventName, ev);
  1659. }
  1660. }
  1661. delete input.inputmask.events[eventName];
  1662. });
  1663. }
  1664. }
  1665. };
  1666. var EventHandlers = {
  1667. keydownEvent: function(e) {
  1668. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  1669. if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI || e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut")) {
  1670. e.preventDefault();
  1671. handleRemove(input, k, pos);
  1672. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  1673. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) {
  1674. e.preventDefault();
  1675. var caretPos = seekNext(getLastValidPosition());
  1676. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  1677. } else if (k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP) {
  1678. e.preventDefault();
  1679. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  1680. } else if ((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || k === 90 && e.ctrlKey) && e.altKey !== true) {
  1681. checkVal(input, true, false, undoValue.split(""));
  1682. $input.trigger("click");
  1683. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) {
  1684. opts.insertMode = !opts.insertMode;
  1685. input.setAttribute("im-insert", opts.insertMode);
  1686. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  1687. if (e.shiftKey === true) {
  1688. if (getTest(pos.begin).match.fn === null) {
  1689. pos.begin = seekNext(pos.begin);
  1690. }
  1691. pos.end = seekPrevious(pos.begin, true);
  1692. pos.begin = seekPrevious(pos.end, true);
  1693. } else {
  1694. pos.begin = seekNext(pos.begin, true);
  1695. pos.end = seekNext(pos.begin, true);
  1696. if (pos.end < getMaskSet().maskLength) pos.end--;
  1697. }
  1698. if (pos.begin < getMaskSet().maskLength) {
  1699. e.preventDefault();
  1700. caret(input, pos.begin, pos.end);
  1701. }
  1702. }
  1703. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  1704. ignorable = $.inArray(k, opts.ignorables) !== -1;
  1705. },
  1706. keypressEvent: function(e, checkval, writeOut, strict, ndx) {
  1707. var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode;
  1708. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1709. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  1710. undoValue = getBuffer().join("");
  1711. setTimeout(function() {
  1712. $input.trigger("change");
  1713. }, 0);
  1714. }
  1715. return true;
  1716. } else {
  1717. if (k) {
  1718. if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
  1719. var pos = checkval ? {
  1720. begin: ndx,
  1721. end: ndx
  1722. } : caret(input), forwardPosition, c = String.fromCharCode(k), offset = 0;
  1723. if (opts._radixDance && opts.numericInput) {
  1724. var caretPos = getBuffer().indexOf(opts.radixPoint.charAt(0)) + 1;
  1725. if (pos.begin <= caretPos) {
  1726. if (k === opts.radixPoint.charCodeAt(0)) offset = 1;
  1727. pos.begin -= 1;
  1728. pos.end -= 1;
  1729. }
  1730. }
  1731. getMaskSet().writeOutBuffer = true;
  1732. var valResult = isValid(pos, c, strict);
  1733. if (valResult !== false) {
  1734. resetMaskSet(true);
  1735. forwardPosition = valResult.caret !== undefined ? valResult.caret : seekNext(valResult.pos.begin ? valResult.pos.begin : valResult.pos);
  1736. getMaskSet().p = forwardPosition;
  1737. }
  1738. forwardPosition = (opts.numericInput && valResult.caret === undefined ? seekPrevious(forwardPosition) : forwardPosition) + offset;
  1739. if (writeOut !== false) {
  1740. setTimeout(function() {
  1741. opts.onKeyValidation.call(input, k, valResult, opts);
  1742. }, 0);
  1743. if (getMaskSet().writeOutBuffer && valResult !== false) {
  1744. var buffer = getBuffer();
  1745. writeBuffer(input, buffer, forwardPosition, e, checkval !== true);
  1746. }
  1747. }
  1748. e.preventDefault();
  1749. if (checkval) {
  1750. if (valResult !== false) valResult.forwardPosition = forwardPosition;
  1751. return valResult;
  1752. }
  1753. }
  1754. }
  1755. },
  1756. pasteEvent: function(e) {
  1757. var input = this, ev = e.originalEvent || e, $input = $(input), inputValue = input.inputmask._valueGet(true), caretPos = caret(input), tempValue;
  1758. if (isRTL) {
  1759. tempValue = caretPos.end;
  1760. caretPos.end = caretPos.begin;
  1761. caretPos.begin = tempValue;
  1762. }
  1763. var valueBeforeCaret = inputValue.substr(0, caretPos.begin), valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  1764. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  1765. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  1766. if (window.clipboardData && window.clipboardData.getData) {
  1767. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  1768. } else if (ev.clipboardData && ev.clipboardData.getData) {
  1769. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  1770. } else return true;
  1771. var pasteValue = inputValue;
  1772. if ($.isFunction(opts.onBeforePaste)) {
  1773. pasteValue = opts.onBeforePaste.call(inputmask, inputValue, opts);
  1774. if (pasteValue === false) {
  1775. return e.preventDefault();
  1776. }
  1777. if (!pasteValue) {
  1778. pasteValue = inputValue;
  1779. }
  1780. }
  1781. checkVal(input, false, false, pasteValue.toString().split(""));
  1782. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  1783. return e.preventDefault();
  1784. },
  1785. inputFallBackEvent: function(e) {
  1786. function radixPointHandler(input, inputValue, caretPos) {
  1787. if (inputValue.charAt(caretPos.begin - 1) === "." && opts.radixPoint !== "") {
  1788. inputValue = inputValue.split("");
  1789. inputValue[caretPos.begin - 1] = opts.radixPoint.charAt(0);
  1790. inputValue = inputValue.join("");
  1791. }
  1792. return inputValue;
  1793. }
  1794. function ieMobileHandler(input, inputValue, caretPos) {
  1795. if (iemobile) {
  1796. var inputChar = inputValue.replace(getBuffer().join(""), "");
  1797. if (inputChar.length === 1) {
  1798. var iv = inputValue.split("");
  1799. iv.splice(caretPos.begin, 0, inputChar);
  1800. inputValue = iv.join("");
  1801. }
  1802. }
  1803. return inputValue;
  1804. }
  1805. var input = this, inputValue = input.inputmask._valueGet();
  1806. if (getBuffer().join("") !== inputValue) {
  1807. var caretPos = caret(input);
  1808. inputValue = radixPointHandler(input, inputValue, caretPos);
  1809. inputValue = ieMobileHandler(input, inputValue, caretPos);
  1810. if (getBuffer().join("") !== inputValue) {
  1811. 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);
  1812. var selection = caretPos, entries = "", isEntry = false;
  1813. if (frontPart !== frontBufferPart) {
  1814. var fpl = (isEntry = frontPart.length >= frontBufferPart.length) ? frontPart.length : frontBufferPart.length, i;
  1815. for (i = 0; frontPart.charAt(i) === frontBufferPart.charAt(i) && i < fpl; i++) ;
  1816. if (isEntry) {
  1817. selection.begin = i - offset;
  1818. entries += frontPart.slice(i, selection.end);
  1819. }
  1820. }
  1821. if (backPart !== backBufferPart) {
  1822. if (backPart.length > backBufferPart.length) {
  1823. entries += backPart.slice(0, 1);
  1824. } else {
  1825. if (backPart.length < backBufferPart.length) {
  1826. selection.end += backBufferPart.length - backPart.length;
  1827. if (!isEntry && opts.radixPoint !== "" && backPart === "" && frontPart.charAt(selection.begin + offset - 1) === opts.radixPoint) {
  1828. selection.begin--;
  1829. entries = opts.radixPoint;
  1830. }
  1831. }
  1832. }
  1833. }
  1834. writeBuffer(input, getBuffer(), {
  1835. begin: selection.begin + offset,
  1836. end: selection.end + offset
  1837. });
  1838. if (entries.length > 0) {
  1839. $.each(entries.split(""), function(ndx, entry) {
  1840. var keypress = new $.Event("keypress");
  1841. keypress.which = entry.charCodeAt(0);
  1842. ignorable = false;
  1843. EventHandlers.keypressEvent.call(input, keypress);
  1844. });
  1845. } else {
  1846. if (selection.begin === selection.end - 1) {
  1847. selection.begin = seekPrevious(selection.begin + 1);
  1848. if (selection.begin === selection.end - 1) {
  1849. caret(input, selection.begin);
  1850. } else {
  1851. caret(input, selection.begin, selection.end);
  1852. }
  1853. }
  1854. var keydown = new $.Event("keydown");
  1855. keydown.keyCode = opts.numericInput ? Inputmask.keyCode.BACKSPACE : Inputmask.keyCode.DELETE;
  1856. EventHandlers.keydownEvent.call(input, keydown);
  1857. }
  1858. e.preventDefault();
  1859. }
  1860. }
  1861. },
  1862. beforeInputEvent: function(e) {
  1863. if (e.cancelable) {
  1864. var input = this;
  1865. switch (e.inputType) {
  1866. case "insertText":
  1867. $.each(e.data.split(""), function(ndx, entry) {
  1868. var keypress = new $.Event("keypress");
  1869. keypress.which = entry.charCodeAt(0);
  1870. ignorable = false;
  1871. EventHandlers.keypressEvent.call(input, keypress);
  1872. });
  1873. return e.preventDefault();
  1874. case "deleteContentBackward":
  1875. var keydown = new $.Event("keydown");
  1876. keydown.keyCode = Inputmask.keyCode.BACKSPACE;
  1877. EventHandlers.keydownEvent.call(input, keydown);
  1878. return e.preventDefault();
  1879. case "deleteContentForward":
  1880. var keydown = new $.Event("keydown");
  1881. keydown.keyCode = Inputmask.keyCode.DELETE;
  1882. EventHandlers.keydownEvent.call(input, keydown);
  1883. return e.preventDefault();
  1884. }
  1885. }
  1886. },
  1887. setValueEvent: function(e) {
  1888. this.inputmask.refreshValue = false;
  1889. var input = this, value = e && e.detail ? e.detail[0] : arguments[1], value = value || input.inputmask._valueGet(true);
  1890. if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask.call(inputmask, value, opts) || value;
  1891. value = value.split("");
  1892. checkVal(input, true, false, value);
  1893. undoValue = getBuffer().join("");
  1894. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  1895. input.inputmask._valueSet("");
  1896. }
  1897. },
  1898. focusEvent: function(e) {
  1899. var input = this, nptValue = input.inputmask._valueGet();
  1900. if (opts.showMaskOnFocus) {
  1901. if (nptValue !== getBuffer().join("")) {
  1902. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1903. } else if (mouseEnter === false) {
  1904. caret(input, seekNext(getLastValidPosition()));
  1905. }
  1906. }
  1907. if (opts.positionCaretOnTab === true && mouseEnter === false) {
  1908. EventHandlers.clickEvent.apply(input, [ e, true ]);
  1909. }
  1910. undoValue = getBuffer().join("");
  1911. },
  1912. mouseleaveEvent: function(e) {
  1913. var input = this;
  1914. mouseEnter = false;
  1915. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  1916. HandleNativePlaceholder(input, originalPlaceholder);
  1917. }
  1918. },
  1919. clickEvent: function(e, tabbed) {
  1920. function doRadixFocus(clickPos) {
  1921. if (opts.radixPoint !== "") {
  1922. var vps = getMaskSet().validPositions;
  1923. if (vps[clickPos] === undefined || vps[clickPos].input === getPlaceholder(clickPos)) {
  1924. if (clickPos < seekNext(-1)) return true;
  1925. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  1926. if (radixPos !== -1) {
  1927. for (var vp in vps) {
  1928. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  1929. return false;
  1930. }
  1931. }
  1932. return true;
  1933. }
  1934. }
  1935. }
  1936. return false;
  1937. }
  1938. var input = this;
  1939. setTimeout(function() {
  1940. if (document.activeElement === input) {
  1941. var selectedCaret = caret(input);
  1942. if (tabbed) {
  1943. if (isRTL) {
  1944. selectedCaret.end = selectedCaret.begin;
  1945. } else {
  1946. selectedCaret.begin = selectedCaret.end;
  1947. }
  1948. }
  1949. if (selectedCaret.begin === selectedCaret.end) {
  1950. switch (opts.positionCaretOnClick) {
  1951. case "none":
  1952. break;
  1953. case "select":
  1954. caret(input, 0, getBuffer().length);
  1955. break;
  1956. case "ignore":
  1957. caret(input, seekNext(getLastValidPosition()));
  1958. break;
  1959. case "radixFocus":
  1960. if (doRadixFocus(selectedCaret.begin)) {
  1961. var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
  1962. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  1963. break;
  1964. }
  1965. default:
  1966. var clickPosition = selectedCaret.begin, lvclickPosition = getLastValidPosition(clickPosition, true), lastPosition = seekNext(lvclickPosition);
  1967. if (clickPosition < lastPosition) {
  1968. caret(input, !isMask(clickPosition, true) && !isMask(clickPosition - 1, true) ? seekNext(clickPosition) : clickPosition);
  1969. } else {
  1970. var lvp = getMaskSet().validPositions[lvclickPosition], tt = getTestTemplate(lastPosition, lvp ? lvp.match.locator : undefined, lvp), placeholder = getPlaceholder(lastPosition, tt.match);
  1971. if (placeholder !== "" && getBuffer()[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true || !isMask(lastPosition, opts.keepStatic) && tt.match.def === placeholder) {
  1972. var newPos = seekNext(lastPosition);
  1973. if (clickPosition >= newPos || clickPosition === lastPosition) {
  1974. lastPosition = newPos;
  1975. }
  1976. }
  1977. caret(input, lastPosition);
  1978. }
  1979. break;
  1980. }
  1981. }
  1982. }
  1983. }, 0);
  1984. },
  1985. cutEvent: function(e) {
  1986. var input = this, $input = $(input), pos = caret(input), ev = e.originalEvent || e;
  1987. var clipboardData = window.clipboardData || ev.clipboardData, clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  1988. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  1989. if (document.execCommand) document.execCommand("copy");
  1990. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  1991. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  1992. },
  1993. blurEvent: function(e) {
  1994. var $input = $(this), input = this;
  1995. if (input.inputmask) {
  1996. HandleNativePlaceholder(input, originalPlaceholder);
  1997. var nptValue = input.inputmask._valueGet(), buffer = getBuffer().slice();
  1998. if (nptValue !== "" || colorMask !== undefined) {
  1999. if (opts.clearMaskOnLostFocus) {
  2000. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2001. buffer = [];
  2002. } else {
  2003. clearOptionalTail(buffer);
  2004. }
  2005. }
  2006. if (isComplete(buffer) === false) {
  2007. setTimeout(function() {
  2008. $input.trigger("incomplete");
  2009. }, 0);
  2010. if (opts.clearIncomplete) {
  2011. resetMaskSet();
  2012. if (opts.clearMaskOnLostFocus) {
  2013. buffer = [];
  2014. } else {
  2015. buffer = getBufferTemplate().slice();
  2016. }
  2017. }
  2018. }
  2019. writeBuffer(input, buffer, undefined, e);
  2020. }
  2021. if (undoValue !== getBuffer().join("")) {
  2022. undoValue = buffer.join("");
  2023. $input.trigger("change");
  2024. }
  2025. }
  2026. },
  2027. mouseenterEvent: function(e) {
  2028. var input = this;
  2029. mouseEnter = true;
  2030. if (document.activeElement !== input && opts.showMaskOnHover) {
  2031. HandleNativePlaceholder(input, (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""));
  2032. }
  2033. },
  2034. submitEvent: function(e) {
  2035. if (undoValue !== getBuffer().join("")) {
  2036. $el.trigger("change");
  2037. }
  2038. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2039. el.inputmask._valueSet("");
  2040. }
  2041. if (opts.clearIncomplete && isComplete(getBuffer()) === false) {
  2042. el.inputmask._valueSet("");
  2043. }
  2044. if (opts.removeMaskOnSubmit) {
  2045. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2046. setTimeout(function() {
  2047. writeBuffer(el, getBuffer());
  2048. }, 0);
  2049. }
  2050. },
  2051. resetEvent: function(e) {
  2052. el.inputmask.refreshValue = true;
  2053. setTimeout(function() {
  2054. $el.trigger("setvalue");
  2055. }, 0);
  2056. }
  2057. };
  2058. function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
  2059. var inputmask = this || input.inputmask, inputValue = nptvl.slice(), charCodes = "", initialNdx = -1, result = undefined;
  2060. function isTemplateMatch(ndx, charCodes) {
  2061. var charCodeNdx = getMaskTemplate(true, 0, false).slice(ndx, seekNext(ndx)).join("").replace(/'/g, "").indexOf(charCodes);
  2062. 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)));
  2063. }
  2064. resetMaskSet();
  2065. if (!strict && opts.autoUnmask !== true) {
  2066. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""), matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  2067. if (matches && matches.length > 0) {
  2068. inputValue.splice(0, matches.length * staticInput.length);
  2069. initialNdx = seekNext(initialNdx);
  2070. }
  2071. } else {
  2072. initialNdx = seekNext(initialNdx);
  2073. }
  2074. if (initialNdx === -1) {
  2075. getMaskSet().p = seekNext(initialNdx);
  2076. initialNdx = 0;
  2077. } else getMaskSet().p = initialNdx;
  2078. inputmask.caretPos = {
  2079. begin: initialNdx
  2080. };
  2081. $.each(inputValue, function(ndx, charCode) {
  2082. if (charCode !== undefined) {
  2083. if (getMaskSet().validPositions[ndx] === undefined && inputValue[ndx] === getPlaceholder(ndx) && isMask(ndx, true) && isValid(ndx, inputValue[ndx], true, undefined, undefined, true) === false) {
  2084. getMaskSet().p++;
  2085. } else {
  2086. var keypress = new $.Event("_checkval");
  2087. keypress.which = charCode.charCodeAt(0);
  2088. charCodes += charCode;
  2089. var lvp = getLastValidPosition(undefined, true);
  2090. if (!isTemplateMatch(initialNdx, charCodes)) {
  2091. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, inputmask.caretPos.begin);
  2092. if (result) {
  2093. initialNdx = inputmask.caretPos.begin + 1;
  2094. charCodes = "";
  2095. }
  2096. } else {
  2097. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, lvp + 1);
  2098. }
  2099. if (result) {
  2100. writeBuffer(undefined, getBuffer(), result.forwardPosition, keypress, false);
  2101. inputmask.caretPos = {
  2102. begin: result.forwardPosition,
  2103. end: result.forwardPosition
  2104. };
  2105. }
  2106. }
  2107. }
  2108. });
  2109. if (writeOut) writeBuffer(input, getBuffer(), result ? result.forwardPosition : undefined, initiatingEvent || new $.Event("checkval"), initiatingEvent && initiatingEvent.type === "input");
  2110. }
  2111. function unmaskedvalue(input) {
  2112. if (input) {
  2113. if (input.inputmask === undefined) {
  2114. return input.value;
  2115. }
  2116. if (input.inputmask && input.inputmask.refreshValue) {
  2117. EventHandlers.setValueEvent.call(input);
  2118. }
  2119. }
  2120. var umValue = [], vps = getMaskSet().validPositions;
  2121. for (var pndx in vps) {
  2122. if (vps[pndx].match && vps[pndx].match.fn != null) {
  2123. umValue.push(vps[pndx].input);
  2124. }
  2125. }
  2126. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  2127. if ($.isFunction(opts.onUnMask)) {
  2128. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  2129. unmaskedValue = opts.onUnMask.call(inputmask, bufferValue, unmaskedValue, opts);
  2130. }
  2131. return unmaskedValue;
  2132. }
  2133. function caret(input, begin, end, notranslate) {
  2134. function translatePosition(pos) {
  2135. if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "") && el) {
  2136. pos = el.inputmask._valueGet().length - pos;
  2137. }
  2138. return pos;
  2139. }
  2140. var range;
  2141. if (begin !== undefined) {
  2142. if ($.isArray(begin)) {
  2143. end = isRTL ? begin[0] : begin[1];
  2144. begin = isRTL ? begin[1] : begin[0];
  2145. }
  2146. if (begin.begin !== undefined) {
  2147. end = isRTL ? begin.begin : begin.end;
  2148. begin = isRTL ? begin.end : begin.begin;
  2149. }
  2150. if (typeof begin === "number") {
  2151. begin = notranslate ? begin : translatePosition(begin);
  2152. end = notranslate ? end : translatePosition(end);
  2153. end = typeof end == "number" ? end : begin;
  2154. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  2155. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  2156. input.inputmask.caretPos = {
  2157. begin: begin,
  2158. end: end
  2159. };
  2160. if (input === document.activeElement) {
  2161. if ("selectionStart" in input) {
  2162. input.selectionStart = begin;
  2163. input.selectionEnd = end;
  2164. } else if (window.getSelection) {
  2165. range = document.createRange();
  2166. if (input.firstChild === undefined || input.firstChild === null) {
  2167. var textNode = document.createTextNode("");
  2168. input.appendChild(textNode);
  2169. }
  2170. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  2171. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  2172. range.collapse(true);
  2173. var sel = window.getSelection();
  2174. sel.removeAllRanges();
  2175. sel.addRange(range);
  2176. } else if (input.createTextRange) {
  2177. range = input.createTextRange();
  2178. range.collapse(true);
  2179. range.moveEnd("character", end);
  2180. range.moveStart("character", begin);
  2181. range.select();
  2182. }
  2183. renderColorMask(input, {
  2184. begin: begin,
  2185. end: end
  2186. });
  2187. }
  2188. }
  2189. } else {
  2190. if ("selectionStart" in input) {
  2191. begin = input.selectionStart;
  2192. end = input.selectionEnd;
  2193. } else if (window.getSelection) {
  2194. range = window.getSelection().getRangeAt(0);
  2195. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  2196. begin = range.startOffset;
  2197. end = range.endOffset;
  2198. }
  2199. } else if (document.selection && document.selection.createRange) {
  2200. range = document.selection.createRange();
  2201. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  2202. end = begin + range.text.length;
  2203. }
  2204. return {
  2205. begin: notranslate ? begin : translatePosition(begin),
  2206. end: notranslate ? end : translatePosition(end)
  2207. };
  2208. }
  2209. }
  2210. function determineLastRequiredPosition(returnDefinition) {
  2211. 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;
  2212. for (pos = lvp + 1; pos < buffer.length; pos++) {
  2213. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2214. ndxIntlzr = testPos.locator.slice();
  2215. positions[pos] = $.extend(true, {}, testPos);
  2216. }
  2217. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  2218. for (pos = bl - 1; pos > lvp; pos--) {
  2219. testPos = positions[pos];
  2220. 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)) {
  2221. bl--;
  2222. } else break;
  2223. }
  2224. return returnDefinition ? {
  2225. l: bl,
  2226. def: positions[bl] ? positions[bl].match : undefined
  2227. } : bl;
  2228. }
  2229. function clearOptionalTail(buffer) {
  2230. buffer.length = 0;
  2231. var template = getMaskTemplate(true, 0, true, undefined, true), lmnt, validPos;
  2232. while (lmnt = template.shift(), lmnt !== undefined) buffer.push(lmnt);
  2233. return buffer;
  2234. }
  2235. function isComplete(buffer) {
  2236. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  2237. if (opts.repeat === "*") return undefined;
  2238. var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp.l);
  2239. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  2240. complete = true;
  2241. for (var i = 0; i <= aml; i++) {
  2242. var test = getTestTemplate(i).match;
  2243. if (test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true || test.fn === null && buffer[i] !== getPlaceholder(i, test)) {
  2244. complete = false;
  2245. break;
  2246. }
  2247. }
  2248. }
  2249. return complete;
  2250. }
  2251. function handleRemove(input, k, pos, strict, fromIsValid) {
  2252. if (opts.numericInput || isRTL) {
  2253. if (k === Inputmask.keyCode.BACKSPACE) {
  2254. k = Inputmask.keyCode.DELETE;
  2255. } else if (k === Inputmask.keyCode.DELETE) {
  2256. k = Inputmask.keyCode.BACKSPACE;
  2257. }
  2258. if (isRTL) {
  2259. var pend = pos.end;
  2260. pos.end = pos.begin;
  2261. pos.begin = pend;
  2262. }
  2263. }
  2264. if (k === Inputmask.keyCode.BACKSPACE && pos.end - pos.begin < 1) {
  2265. pos.begin = seekPrevious(pos.begin);
  2266. if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
  2267. pos.begin--;
  2268. }
  2269. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  2270. pos.end = isMask(pos.end, true) && (getMaskSet().validPositions[pos.end] && getMaskSet().validPositions[pos.end].input !== opts.radixPoint) ? pos.end + 1 : seekNext(pos.end) + 1;
  2271. if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
  2272. pos.end++;
  2273. }
  2274. }
  2275. revalidateMask(pos);
  2276. if (strict !== true && opts.keepStatic !== false || opts.regex !== null) {
  2277. var result = alternate(true);
  2278. if (result) {
  2279. var newPos = result.caret !== undefined ? result.caret : result.pos ? seekNext(result.pos.begin ? result.pos.begin : result.pos) : getLastValidPosition(-1, true);
  2280. if (k !== Inputmask.keyCode.DELETE || pos.begin > newPos) {
  2281. pos.begin == newPos;
  2282. }
  2283. }
  2284. }
  2285. var lvp = getLastValidPosition(pos.begin, true);
  2286. if (lvp < pos.begin || pos.begin === -1) {
  2287. getMaskSet().p = seekNext(lvp);
  2288. } else if (strict !== true) {
  2289. getMaskSet().p = pos.begin;
  2290. if (fromIsValid !== true) {
  2291. while (getMaskSet().p < lvp && getMaskSet().validPositions[getMaskSet().p] === undefined) {
  2292. getMaskSet().p++;
  2293. }
  2294. }
  2295. }
  2296. }
  2297. function initializeColorMask(input) {
  2298. var computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2299. function findCaretPos(clientx) {
  2300. var e = document.createElement("span"), caretPos;
  2301. for (var style in computedStyle) {
  2302. if (isNaN(style) && style.indexOf("font") !== -1) {
  2303. e.style[style] = computedStyle[style];
  2304. }
  2305. }
  2306. e.style.textTransform = computedStyle.textTransform;
  2307. e.style.letterSpacing = computedStyle.letterSpacing;
  2308. e.style.position = "absolute";
  2309. e.style.height = "auto";
  2310. e.style.width = "auto";
  2311. e.style.visibility = "hidden";
  2312. e.style.whiteSpace = "nowrap";
  2313. document.body.appendChild(e);
  2314. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2315. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2316. e.innerHTML += inputText.charAt(caretPos) || "_";
  2317. if (e.offsetWidth >= clientx) {
  2318. var offset1 = clientx - previousWidth;
  2319. var offset2 = e.offsetWidth - clientx;
  2320. e.innerHTML = inputText.charAt(caretPos);
  2321. offset1 -= e.offsetWidth / 3;
  2322. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2323. break;
  2324. }
  2325. previousWidth = e.offsetWidth;
  2326. }
  2327. document.body.removeChild(e);
  2328. return caretPos;
  2329. }
  2330. var template = document.createElement("div");
  2331. template.style.width = computedStyle.width;
  2332. template.style.textAlign = computedStyle.textAlign;
  2333. colorMask = document.createElement("div");
  2334. input.inputmask.colorMask = colorMask;
  2335. colorMask.className = "im-colormask";
  2336. input.parentNode.insertBefore(colorMask, input);
  2337. input.parentNode.removeChild(input);
  2338. colorMask.appendChild(input);
  2339. colorMask.appendChild(template);
  2340. input.style.left = template.offsetLeft + "px";
  2341. $(colorMask).on("mouseleave", function(e) {
  2342. return EventHandlers.mouseleaveEvent.call(input, [ e ]);
  2343. });
  2344. $(colorMask).on("mouseenter", function(e) {
  2345. return EventHandlers.mouseenterEvent.call(input, [ e ]);
  2346. });
  2347. $(colorMask).on("click", function(e) {
  2348. caret(input, findCaretPos(e.clientX));
  2349. return EventHandlers.clickEvent.call(input, [ e ]);
  2350. });
  2351. }
  2352. Inputmask.prototype.positionColorMask = function(input, template) {
  2353. input.style.left = template.offsetLeft + "px";
  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. });