inputmask.js 100 KB

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