inputmask.js 97 KB

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