inputmask.js 98 KB

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