inputmask.js 112 KB

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