inputmask.js 103 KB

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