inputmask.js 105 KB

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