inputmask.js 103 KB

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