inputmask.js 105 KB

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