inputmask.js 98 KB

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