inputmask.js 104 KB

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