inputmask.js 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750
  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: key, 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.getElementById(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) { //ndxInitializer contains a set of indexes to speedup searches in the mtokens
  894. function handleMatch(match, loopNdx, quantifierRecurse) {
  895. function resolveNdxInitializer(pos, alternateNdx) {
  896. var previousMatch = getMaskSet().validPositions[pos];
  897. if (previousMatch === undefined) {
  898. if (getMaskSet().tests[pos]) {
  899. $.each(getMaskSet().tests[pos], function(ndx, lmnt) {
  900. if (lmnt.alternation && lmnt.locator[lmnt.alternation].toString().indexOf(alternateNdx) !== -1) {
  901. previousMatch = lmnt;
  902. return false;
  903. }
  904. });
  905. }
  906. }
  907. return previousMatch ? previousMatch.locator.slice(previousMatch.alternation + 1) : [];
  908. }
  909. if (testPos > 10000) {
  910. 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;
  911. }
  912. if (testPos === pos && match.matches === undefined) {
  913. matches.push({
  914. "match": match,
  915. "locator": loopNdx.reverse()
  916. });
  917. return true;
  918. } else if (match.matches !== undefined) {
  919. if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier
  920. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);
  921. if (match) return true;
  922. } else if (match.isOptional) {
  923. var optionalToken = match;
  924. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  925. if (match) {
  926. latestMatch = matches[matches.length - 1].match;
  927. isFirstMatch = $.inArray(latestMatch, optionalToken.matches) === 0;
  928. if (isFirstMatch) {
  929. insertStop = true; //insert a stop
  930. testPos = pos; //match the position after the group
  931. } else return true;
  932. }
  933. } else if (match.isAlternator) {
  934. var alternateToken = match,
  935. malternateMatches = [],
  936. maltMatches,
  937. currentMatches = matches.slice(),
  938. loopNdxCnt = loopNdx.length;
  939. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  940. if (altIndex === -1 || typeof altIndex === "string") {
  941. var currentPos = testPos,
  942. ndxInitializerClone = ndxInitializer.slice(),
  943. altIndexArr = [],
  944. amndx;
  945. if (typeof altIndex == "string") {
  946. altIndexArr = altIndex.split(",");
  947. } else {
  948. for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  949. altIndexArr.push(amndx);
  950. }
  951. }
  952. for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
  953. amndx = parseInt(altIndexArr[ndx]);
  954. matches = [];
  955. //set the correct ndxInitializer
  956. ndxInitializer = resolveNdxInitializer(testPos, amndx);
  957. match = handleMatch(alternateToken.matches[amndx] || maskToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  958. if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
  959. var ntndx = maskToken.matches.indexOf(match) + 1;
  960. if (maskToken.matches.length > ntndx) {
  961. match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);
  962. if (match) {
  963. altIndexArr.push(ntndx.toString());
  964. $.each(matches, function(ndx, lmnt) {
  965. lmnt.alternation = loopNdx.length - 1;
  966. });
  967. }
  968. }
  969. }
  970. maltMatches = matches.slice();
  971. testPos = currentPos;
  972. matches = [];
  973. //cloneback
  974. for (var i = 0; i < ndxInitializerClone.length; i++) {
  975. ndxInitializer[i] = ndxInitializerClone[i];
  976. }
  977. //fuzzy merge matches
  978. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  979. var altMatch = maltMatches[ndx1];
  980. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  981. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  982. var altMatch2 = malternateMatches[ndx2];
  983. //verify equality
  984. if (altMatch.match.def === altMatch2.match.def && (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1)) {
  985. if (altMatch.match.mask === altMatch2.match.mask) {
  986. maltMatches.splice(ndx1, 1);
  987. ndx1--;
  988. }
  989. if (altMatch2.locator[altMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
  990. altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation];
  991. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  992. }
  993. break;
  994. }
  995. }
  996. }
  997. malternateMatches = malternateMatches.concat(maltMatches);
  998. }
  999. if (typeof altIndex == "string") { //filter matches
  1000. malternateMatches = $.map(malternateMatches, function(lmnt, ndx) {
  1001. if (isFinite(ndx)) {
  1002. var mamatch,
  1003. alternation = lmnt.alternation,
  1004. altLocArr = lmnt.locator[alternation].toString().split(",");
  1005. lmnt.locator[alternation] = undefined;
  1006. lmnt.alternation = undefined;
  1007. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  1008. mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
  1009. if (mamatch) { //rebuild the locator with valid entries
  1010. if (lmnt.locator[alternation] !== undefined) {
  1011. lmnt.locator[alternation] += ",";
  1012. lmnt.locator[alternation] += altLocArr[alndx];
  1013. } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  1014. lmnt.alternation = alternation;
  1015. }
  1016. }
  1017. if (lmnt.locator[alternation] !== undefined) return lmnt;
  1018. }
  1019. });
  1020. }
  1021. matches = currentMatches.concat(malternateMatches);
  1022. testPos = pos;
  1023. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate - needed for non-greedy option
  1024. } else {
  1025. // if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  1026. match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  1027. // } else match = false;
  1028. }
  1029. if (match) return true;
  1030. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  1031. var qt = match;
  1032. for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0;
  1033. (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  1034. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  1035. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
  1036. if (match) {
  1037. //get latest match
  1038. latestMatch = matches[matches.length - 1].match;
  1039. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  1040. isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  1041. if (isFirstMatch) { //search for next possible match
  1042. if (qndx > (qt.quantifier.min - 1)) {
  1043. insertStop = true;
  1044. testPos = pos; //match the position after the group
  1045. break; //stop quantifierloop
  1046. } else return true;
  1047. } else {
  1048. return true;
  1049. }
  1050. }
  1051. }
  1052. } else {
  1053. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  1054. if (match) return true;
  1055. }
  1056. } else testPos++;
  1057. }
  1058. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0); tndx < maskToken.matches.length; tndx++) {
  1059. if (maskToken.matches[tndx].isQuantifier !== true) {
  1060. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  1061. if (match && testPos === pos) {
  1062. return match;
  1063. } else if (testPos > pos) {
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. if (pos > -1) {
  1070. if (cacheable === true && getMaskSet().tests[pos]) {
  1071. return getMaskSet().tests[pos];
  1072. }
  1073. if (ndxIntlzr === undefined) {
  1074. var previousPos = pos - 1,
  1075. test;
  1076. while ((test = getMaskSet().validPositions[previousPos]) === undefined && previousPos > -1) {
  1077. if (getMaskSet().tests[previousPos] && (test = getMaskSet().tests[previousPos][0]) !== undefined) {
  1078. break;
  1079. }
  1080. previousPos--;
  1081. }
  1082. if (test !== undefined && previousPos > -1) {
  1083. testPos = previousPos;
  1084. ndxInitializer = test.locator.slice();
  1085. }
  1086. }
  1087. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1088. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  1089. if ((match && testPos === pos) || testPos > pos) {
  1090. break;
  1091. }
  1092. }
  1093. if (matches.length === 0 || insertStop) {
  1094. matches.push({
  1095. "match": {
  1096. fn: null,
  1097. cardinality: 0,
  1098. optionality: true,
  1099. casing: null,
  1100. def: ""
  1101. },
  1102. "locator": []
  1103. });
  1104. }
  1105. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1106. // console.log(pos + " - " + JSON.stringify(matches));
  1107. return getMaskSet().tests[pos];
  1108. }
  1109. }
  1110. function getBufferTemplate() {
  1111. if (getMaskSet()._buffer === undefined) {
  1112. //generate template
  1113. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1114. }
  1115. return getMaskSet()._buffer;
  1116. }
  1117. function getBuffer(noCache) {
  1118. if (getMaskSet().buffer === undefined || noCache === true) {
  1119. if (noCache === true) getMaskSet().tests = {};
  1120. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1121. }
  1122. return getMaskSet().buffer;
  1123. }
  1124. function refreshFromBuffer(start, end, buffer) {
  1125. var i;
  1126. buffer = buffer;
  1127. if (start === true) {
  1128. resetMaskSet();
  1129. start = 0;
  1130. end = buffer.length;
  1131. } else {
  1132. for (i = start; i < end; i++) {
  1133. delete getMaskSet().validPositions[i];
  1134. delete getMaskSet().tests[i];
  1135. }
  1136. }
  1137. for (i = start; i < end; i++) {
  1138. resetMaskSet(true); //prevents clobber from the buffer
  1139. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1140. isValid(i, buffer[i], true, true);
  1141. }
  1142. }
  1143. }
  1144. function casing(elem, test) {
  1145. switch (test.casing) {
  1146. case "upper":
  1147. elem = elem.toUpperCase();
  1148. break;
  1149. case "lower":
  1150. elem = elem.toLowerCase();
  1151. break;
  1152. }
  1153. return elem;
  1154. }
  1155. function checkAlternationMatch(altArr1, altArr2) {
  1156. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1157. isMatch = false;
  1158. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1159. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1160. isMatch = true;
  1161. break;
  1162. }
  1163. }
  1164. return isMatch;
  1165. }
  1166. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  1167. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  1168. function _isValid(position, c, strict, fromSetValid) {
  1169. var rslt = false;
  1170. $.each(getTests(position), function(ndx, tst) {
  1171. var test = tst.match;
  1172. var loopend = c ? 1 : 0,
  1173. chrs = "";
  1174. for (var i = test.cardinality; i > loopend; i--) {
  1175. chrs += getBufferElement(position - (i - 1));
  1176. }
  1177. if (c) {
  1178. chrs += c;
  1179. }
  1180. //make sure the buffer is set and correct
  1181. getBuffer(true);
  1182. //return is false or a json object => { pos: ??, c: ??} or true
  1183. rslt = test.fn != null ?
  1184. test.fn.test(chrs, getMaskSet(), position, strict, opts) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
  1185. {
  1186. c: test.def,
  1187. pos: position
  1188. } : false;
  1189. if (rslt !== false) {
  1190. var elem = rslt.c !== undefined ? rslt.c : c;
  1191. elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ? test.def : elem;
  1192. var validatedPos = position,
  1193. possibleModifiedBuffer = getBuffer();
  1194. if (rslt.remove !== undefined) { //remove position(s)
  1195. if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
  1196. $.each(rslt.remove.sort(function(a, b) {
  1197. return b - a;
  1198. }), function(ndx, lmnt) {
  1199. stripValidPositions(lmnt, lmnt + 1, true);
  1200. });
  1201. }
  1202. if (rslt.insert !== undefined) { //insert position(s)
  1203. if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
  1204. $.each(rslt.insert.sort(function(a, b) {
  1205. return a - b;
  1206. }), function(ndx, lmnt) {
  1207. isValid(lmnt.pos, lmnt.c, true);
  1208. });
  1209. }
  1210. if (rslt.refreshFromBuffer) {
  1211. var refresh = rslt.refreshFromBuffer;
  1212. strict = true;
  1213. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
  1214. if (rslt.pos === undefined && rslt.c === undefined) {
  1215. rslt.pos = getLastValidPosition();
  1216. return false; //breakout if refreshFromBuffer && nothing to insert
  1217. }
  1218. validatedPos = rslt.pos !== undefined ? rslt.pos : position;
  1219. if (validatedPos !== position) {
  1220. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1221. return false;
  1222. }
  1223. } else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
  1224. validatedPos = rslt.pos;
  1225. refreshFromBuffer(position, validatedPos, getBuffer().slice());
  1226. if (validatedPos !== position) {
  1227. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1228. return false;
  1229. }
  1230. }
  1231. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1232. return false; //breakout if nothing to insert
  1233. }
  1234. if (ndx > 0) {
  1235. resetMaskSet(true);
  1236. }
  1237. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  1238. "input": casing(elem, test)
  1239. }), fromSetValid)) {
  1240. rslt = false;
  1241. }
  1242. return false; //break from $.each
  1243. }
  1244. });
  1245. return rslt;
  1246. }
  1247. function alternate(pos, c, strict, fromSetValid) {
  1248. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1249. lastAlt,
  1250. alternation,
  1251. isValidRslt,
  1252. altPos, i, validPos;
  1253. //find last modified alternation
  1254. for (var lAlt = getLastValidPosition(); lAlt >= 0; lAlt--) {
  1255. altPos = getMaskSet().validPositions[lAlt];
  1256. if (altPos && altPos.alternation !== undefined) {
  1257. lastAlt = lAlt;
  1258. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1259. if (getTestTemplate(lastAlt).locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. if (alternation !== undefined) {
  1265. //find first decision making position
  1266. lastAlt = parseInt(lastAlt);
  1267. for (var decisionPos in getMaskSet().validPositions) {
  1268. decisionPos = parseInt(decisionPos);
  1269. altPos = getMaskSet().validPositions[decisionPos];
  1270. if (decisionPos >= lastAlt && altPos.alternation !== undefined) {
  1271. var altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].toString().split(","),
  1272. decisionTaker = altPos.locator[alternation] !== undefined ? altPos.locator[alternation] : altNdxs[0]; //no match in the alternations (length mismatch)
  1273. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1274. decisionTaker = decisionTaker.split(",")[0];
  1275. }
  1276. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1277. if (decisionTaker < altNdxs[mndx]) {
  1278. var possibilityPos, possibilities;
  1279. for (var dp = decisionPos; dp >= 0; dp--) {
  1280. possibilityPos = getMaskSet().validPositions[dp];
  1281. if (possibilityPos !== undefined) {
  1282. possibilities = possibilityPos.locator[alternation]; //store to reset
  1283. //possibilityPos.alternation = undefined;
  1284. possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]);
  1285. break;
  1286. }
  1287. }
  1288. if (decisionTaker !== possibilityPos.locator[alternation]) {
  1289. var validInputs = [],
  1290. staticInputsBeforePos = 0;
  1291. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1292. validPos = getMaskSet().validPositions[i];
  1293. if (validPos && validPos.match.fn != null) {
  1294. validInputs.push(validPos.input);
  1295. } else if (i < pos) staticInputsBeforePos++;
  1296. delete getMaskSet().validPositions[i];
  1297. delete getMaskSet().tests[i];
  1298. }
  1299. resetMaskSet(true); //clear getbuffer
  1300. opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
  1301. isValidRslt = true;
  1302. while (validInputs.length > 0) {
  1303. var input = validInputs.shift();
  1304. if (input !== opts.skipOptionalPartCharacter) {
  1305. if (!(isValidRslt = isValid(getLastValidPosition() + 1, input, false, true))) {
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. possibilityPos.alternation = alternation;
  1311. possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete
  1312. if (isValidRslt) {
  1313. var targetLvp = getLastValidPosition(pos) + 1;
  1314. var staticInputsBeforePosAlternate = 0;
  1315. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1316. validPos = getMaskSet().validPositions[i];
  1317. if ((validPos === undefined || validPos.match.fn == null) && i < pos) {
  1318. staticInputsBeforePosAlternate++;
  1319. }
  1320. }
  1321. pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
  1322. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid);
  1323. }
  1324. opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength
  1325. if (!isValidRslt) {
  1326. resetMaskSet();
  1327. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1328. } else return isValidRslt;
  1329. }
  1330. }
  1331. }
  1332. break;
  1333. }
  1334. }
  1335. }
  1336. return false;
  1337. }
  1338. //set alternator choice on previous skipped placeholder positions
  1339. function trackbackAlternations(originalPos, newPos) {
  1340. var vp = getMaskSet().validPositions[newPos],
  1341. targetLocator = vp.locator,
  1342. tll = targetLocator.length;
  1343. for (var ps = originalPos; ps < newPos; ps++) {
  1344. if (!isMask(ps)) {
  1345. var tests = getTests(ps),
  1346. bestMatch = tests[0],
  1347. equality = -1;
  1348. $.each(tests, function(ndx, tst) {
  1349. for (var i = 0; i < tll; i++) {
  1350. if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(",")) && equality < i) {
  1351. equality = i;
  1352. bestMatch = tst;
  1353. }
  1354. }
  1355. });
  1356. setValidPosition(ps, $.extend({}, bestMatch, {
  1357. "input": bestMatch.match.def
  1358. }), true);
  1359. }
  1360. }
  1361. }
  1362. //Check for a nonmask before the pos
  1363. var buffer = getBuffer();
  1364. //find previous valid
  1365. for (var pndx = pos - 1; pndx > -1; pndx--) {
  1366. if (getMaskSet().validPositions[pndx]) {
  1367. break;
  1368. }
  1369. }
  1370. ////fill missing nonmask and valid placeholders
  1371. pndx++;
  1372. for (; pndx < pos; pndx++) {
  1373. //console.log("missing " + pndx + " " + buffer[pndx] + " ismask " + isMask(pndx) + " plchldr " + getPlaceholder(pndx) + " nrt " + getTests(pndx).len);
  1374. 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
  1375. {
  1376. //console.log("inject " + pndx + " " + buffer[pndx]);
  1377. _isValid(pndx, buffer[pndx], true);
  1378. }
  1379. }
  1380. var maskPos = pos,
  1381. result = false,
  1382. positionsClone = $.extend(true, {}, getMaskSet().validPositions); //clone the currentPositions
  1383. //if (fromSetValid && maskPos >= getMaskLength()) {
  1384. // resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length
  1385. //}
  1386. if (maskPos < getMaskLength()) {
  1387. result = _isValid(maskPos, c, strict, fromSetValid);
  1388. if ((!strict || fromSetValid) && result === false) {
  1389. var currentPosValid = getMaskSet().validPositions[maskPos];
  1390. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1391. result = {
  1392. "caret": seekNext(maskPos)
  1393. };
  1394. } else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos)) { //does the input match on a further position?
  1395. for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1396. result = _isValid(nPos, c, strict, fromSetValid);
  1397. if (result !== false) {
  1398. trackbackAlternations(maskPos, nPos);
  1399. maskPos = nPos;
  1400. break;
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic
  1407. result = alternate(pos, c, strict, fromSetValid);
  1408. }
  1409. if (result === true) {
  1410. result = {
  1411. "pos": maskPos
  1412. };
  1413. }
  1414. if ($.isFunction(opts.postValidation) && result !== false && !strict) {
  1415. var postValidResult = opts.postValidation(getBuffer(true), opts);
  1416. if (!postValidResult) {
  1417. resetMaskSet(true);
  1418. getMaskSet().validPositions = $.extend(true, {}, positionsClone); //revert validation changes
  1419. result = false;
  1420. } else if (postValidResult.refreshFromBuffer) {
  1421. var refresh = postValidResult.refreshFromBuffer;
  1422. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postValidResult.buffer);
  1423. resetMaskSet(true);
  1424. result = postValidResult;
  1425. }
  1426. }
  1427. return result;
  1428. }
  1429. function isMask(pos) {
  1430. var test = getTest(pos);
  1431. if (test.fn != null) {
  1432. return test.fn;
  1433. } else if (pos > -1 && !opts.keepStatic && getMaskSet().validPositions[pos] === undefined) {
  1434. var tests = getTests(pos, undefined, undefined, true);
  1435. return tests.length > 2;
  1436. }
  1437. return false;
  1438. }
  1439. function getMaskLength() {
  1440. var maskLength;
  1441. maxLength = el !== undefined ? el.maxLength : undefined;
  1442. if (maxLength === -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  1443. var pos, lvp = getLastValidPosition(),
  1444. testPos = getMaskSet().validPositions[lvp],
  1445. ndxIntlzr = testPos !== undefined ? testPos.locator.slice() : undefined;
  1446. for (pos = lvp + 1; testPos === undefined || (testPos.match.fn !== null || (testPos.match.fn === null && testPos.match.def !== "")); pos++) {
  1447. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1448. ndxIntlzr = testPos.locator.slice();
  1449. }
  1450. var lastTest = getTest(pos - 1);
  1451. maskLength = (lastTest.def !== "") ? pos : pos - 1;
  1452. return (maxLength === undefined || maskLength < maxLength) ? maskLength : maxLength;
  1453. }
  1454. function seekNext(pos, newBlock) {
  1455. var maskL = getMaskLength();
  1456. if (pos >= maskL) return maskL;
  1457. var position = pos;
  1458. while (++position < maskL && ((newBlock === true && (getTest(position).newBlockMarker !== true || !isMask(position))) || (newBlock !== true && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)))) {}
  1459. return position;
  1460. }
  1461. function seekPrevious(pos, newBlock) {
  1462. var position = pos;
  1463. if (position <= 0) return 0;
  1464. while (--position > 0 && ((newBlock === true && getTest(position).newBlockMarker !== true) || (newBlock !== true && !isMask(position)))) {}
  1465. return position;
  1466. }
  1467. function getBufferElement(position) {
  1468. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1469. }
  1470. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1471. if (event && $.isFunction(opts.onBeforeWrite)) {
  1472. var result = opts.onBeforeWrite.call(input, event, buffer, caretPos, opts);
  1473. if (result) {
  1474. if (result.refreshFromBuffer) {
  1475. var refresh = result.refreshFromBuffer;
  1476. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1477. buffer = getBuffer(true);
  1478. }
  1479. //only alter when intented !== undefined
  1480. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1481. }
  1482. }
  1483. input.inputmask._valueSet(buffer.join(""));
  1484. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1485. caret(input, caretPos);
  1486. }
  1487. if (triggerInputEvent === true) {
  1488. skipInputEvent = true;
  1489. $(input).trigger("input");
  1490. }
  1491. }
  1492. function getPlaceholder(pos, test) {
  1493. test = test || getTest(pos);
  1494. if (test.placeholder !== undefined) {
  1495. return test.placeholder;
  1496. } else if (test.fn === null) {
  1497. if (pos > -1 && !opts.keepStatic && getMaskSet().validPositions[pos] === undefined) {
  1498. var tests = getTests(pos),
  1499. hasAlternations = false,
  1500. prevTest;
  1501. for (var i = 0; i < tests.length; i++) {
  1502. if (prevTest && tests[i].match.def !== "" && (tests[i].match.def !== prevTest.match.def && (tests[i].alternation === undefined || tests[i].alternation === prevTest.alternation))) {
  1503. hasAlternations = true;
  1504. break;
  1505. }
  1506. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true) {
  1507. prevTest = tests[i];
  1508. }
  1509. }
  1510. if (hasAlternations) {
  1511. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1512. }
  1513. }
  1514. return test.def;
  1515. }
  1516. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1517. }
  1518. function checkVal(input, writeOut, strict, nptvl) {
  1519. var inputValue = nptvl.slice(),
  1520. charCodes = "",
  1521. initialNdx = 0;
  1522. function isTemplateMatch() {
  1523. var isMatch = false;
  1524. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes);
  1525. if (charCodeNdx !== -1 && !isMask(initialNdx)) {
  1526. isMatch = true;
  1527. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  1528. for (var i = 0; i < bufferTemplateArr.length; i++) {
  1529. if (bufferTemplateArr[i] !== " ") {
  1530. isMatch = false;
  1531. break;
  1532. }
  1533. }
  1534. }
  1535. return isMatch;
  1536. }
  1537. resetMaskSet();
  1538. getMaskSet().p = seekNext(-1);
  1539. // if (writeOut) input.inputmask._valueSet(""); //initial clear
  1540. if (!strict) {
  1541. if (opts.autoUnmask !== true) {
  1542. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  1543. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1544. if (matches && matches.length > 0) {
  1545. inputValue.splice(0, matches.length * staticInput.length);
  1546. initialNdx = seekNext(initialNdx);
  1547. }
  1548. } else {
  1549. initialNdx = seekNext(initialNdx);
  1550. }
  1551. }
  1552. $.each(inputValue, function(ndx, charCode) {
  1553. var keypress = $.Event("keypress");
  1554. keypress.which = charCode.charCodeAt(0);
  1555. charCodes += charCode;
  1556. var lvp = getLastValidPosition(undefined, true),
  1557. lvTest = getMaskSet().validPositions[lvp],
  1558. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1559. if (!isTemplateMatch() || strict || opts.autoUnmask) {
  1560. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1561. keypressEvent.call(input, keypress, true, false, strict, pos);
  1562. initialNdx = pos + 1;
  1563. charCodes = "";
  1564. } else {
  1565. keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1566. }
  1567. });
  1568. if (writeOut) {
  1569. writeBuffer(input, getBuffer(), document.activeElement === input ? seekNext(getLastValidPosition(0)) : undefined, $.Event("checkval"));
  1570. }
  1571. }
  1572. function unmaskedvalue(input) {
  1573. if (input && input.inputmask === undefined) {
  1574. return input.value;
  1575. }
  1576. var umValue = [],
  1577. vps = getMaskSet().validPositions;
  1578. for (var pndx in vps) {
  1579. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1580. umValue.push(vps[pndx].input);
  1581. }
  1582. }
  1583. var unmaskedValue = umValue.length === 0 ? null : (isRTL ? umValue.reverse() : umValue).join("");
  1584. if (unmaskedValue !== null) {
  1585. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1586. if ($.isFunction(opts.onUnMask)) {
  1587. unmaskedValue = (opts.onUnMask.call(input, bufferValue, unmaskedValue, opts) || unmaskedValue);
  1588. }
  1589. }
  1590. return unmaskedValue;
  1591. }
  1592. function caret(input, begin, end) {
  1593. function translatePosition(pos) {
  1594. if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1595. 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)
  1596. pos = bffrLght - pos;
  1597. }
  1598. return pos;
  1599. }
  1600. var range;
  1601. if (typeof begin === "number") {
  1602. begin = translatePosition(begin);
  1603. end = translatePosition(end);
  1604. end = (typeof end == "number") ? end : begin;
  1605. // if (!$(input).is(":visible")) {
  1606. // return;
  1607. // }
  1608. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1609. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1610. if (!androidchrome && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1611. if (input.setSelectionRange) {
  1612. input.selectionStart = begin;
  1613. input.selectionEnd = end;
  1614. } else if (window.getSelection) {
  1615. range = document.createRange();
  1616. if (input.firstChild === undefined) {
  1617. var textNode = document.createTextNode("");
  1618. input.appendChild(textNode);
  1619. }
  1620. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1621. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1622. range.collapse(true);
  1623. var sel = window.getSelection();
  1624. sel.removeAllRanges();
  1625. sel.addRange(range);
  1626. //input.focus();
  1627. } else if (input.createTextRange) {
  1628. range = input.createTextRange();
  1629. range.collapse(true);
  1630. range.moveEnd("character", end);
  1631. range.moveStart("character", begin);
  1632. range.select();
  1633. }
  1634. } else {
  1635. if (input.setSelectionRange) {
  1636. begin = input.selectionStart;
  1637. end = input.selectionEnd;
  1638. } else if (window.getSelection) {
  1639. range = window.getSelection().getRangeAt(0);
  1640. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1641. begin = range.startOffset;
  1642. end = range.endOffset;
  1643. }
  1644. } else if (document.selection && document.selection.createRange) {
  1645. range = document.selection.createRange();
  1646. begin = 0 - range.duplicate().moveStart("character", -100000);
  1647. end = begin + range.text.length;
  1648. }
  1649. /*eslint-disable consistent-return */
  1650. return {
  1651. "begin": translatePosition(begin),
  1652. "end": translatePosition(end)
  1653. };
  1654. /*eslint-enable consistent-return */
  1655. }
  1656. }
  1657. function determineLastRequiredPosition(returnDefinition) {
  1658. var buffer = getBuffer(),
  1659. bl = buffer.length,
  1660. pos, lvp = getLastValidPosition(),
  1661. positions = {},
  1662. lvTest = getMaskSet().validPositions[lvp],
  1663. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1664. testPos;
  1665. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1666. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1667. ndxIntlzr = testPos.locator.slice();
  1668. positions[pos] = $.extend(true, {}, testPos);
  1669. }
  1670. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1671. for (pos = bl - 1; pos > lvp; pos--) {
  1672. testPos = positions[pos];
  1673. if ((testPos.match.optionality ||
  1674. testPos.match.optionalQuantifier ||
  1675. (lvTestAlt && ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1676. (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)) {
  1677. bl--;
  1678. } else break;
  1679. }
  1680. return returnDefinition ? {
  1681. "l": bl,
  1682. "def": positions[bl] ? positions[bl].match : undefined
  1683. } : bl;
  1684. }
  1685. function clearOptionalTail(buffer) {
  1686. var rl = determineLastRequiredPosition(),
  1687. lmib = buffer.length - 1;
  1688. for (; lmib > rl; lmib--) {
  1689. if (isMask(lmib)) break; //fixme ismask is not good enough
  1690. }
  1691. buffer.splice(rl, lmib + 1 - rl);
  1692. return buffer;
  1693. }
  1694. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1695. if ($.isFunction(opts.isComplete)) return opts.isComplete.call(el, buffer, opts);
  1696. if (opts.repeat === "*") return undefined;
  1697. var complete = false,
  1698. lrp = determineLastRequiredPosition(true),
  1699. aml = seekPrevious(lrp.l);
  1700. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1701. complete = true;
  1702. for (var i = 0; i <= aml; i++) {
  1703. var test = getTestTemplate(i).match;
  1704. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1705. complete = false;
  1706. break;
  1707. }
  1708. }
  1709. }
  1710. return complete;
  1711. }
  1712. function isSelection(begin, end) {
  1713. return isRTL ? (begin - end) > 1 || ((begin - end) === 1 && opts.insertMode) :
  1714. (end - begin) > 1 || ((end - begin) === 1 && opts.insertMode);
  1715. }
  1716. function wrapEventRuler(eventHandler) {
  1717. return function(e) {
  1718. // console.log("triggered " + e.type);
  1719. var inComposition = false,
  1720. keydownPressed = false;
  1721. if (this.inputmask === undefined) { //happens when cloning an object with jquery.clone
  1722. var imOpts = $.data(this, "_inputmask_opts");
  1723. if (imOpts)(new Inputmask(imOpts)).mask(this);
  1724. else $(this).off(".inputmask");
  1725. } 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))))) {
  1726. e.preventDefault();
  1727. } else {
  1728. switch (e.type) {
  1729. case "input":
  1730. if (skipInputEvent === true || inComposition === true) {
  1731. skipInputEvent = false;
  1732. return e.preventDefault();
  1733. }
  1734. keydownPressed = false;
  1735. break;
  1736. case "keydown":
  1737. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1738. skipKeyPressEvent = false;
  1739. inComposition = false;
  1740. keydownPressed = true;
  1741. break;
  1742. case "keypress":
  1743. if (skipKeyPressEvent === true) {
  1744. return e.preventDefault();
  1745. }
  1746. skipKeyPressEvent = true;
  1747. break;
  1748. case "compositionstart":
  1749. inComposition = true;
  1750. break;
  1751. case "compositionupdate":
  1752. skipInputEvent = keydownPressed;
  1753. break;
  1754. case "compositionend":
  1755. inComposition = false;
  1756. keydownPressed = false;
  1757. break;
  1758. case "cut":
  1759. skipInputEvent = true;
  1760. break;
  1761. }
  1762. //console.log("executed " + e.type);
  1763. return eventHandler.apply(this, arguments);
  1764. }
  1765. };
  1766. }
  1767. function patchValueProperty(npt) {
  1768. var valueGet;
  1769. var valueSet;
  1770. function patchValhook(type) {
  1771. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  1772. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
  1773. return elem.value;
  1774. };
  1775. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
  1776. elem.value = value;
  1777. return elem;
  1778. };
  1779. $.valHooks[type] = {
  1780. get: function(elem) {
  1781. if (elem.inputmask) {
  1782. if (elem.inputmask.opts.autoUnmask) {
  1783. return elem.inputmask.unmaskedvalue();
  1784. } else {
  1785. var result = valhookGet(elem),
  1786. maskset = elem.inputmask.maskset,
  1787. bufferTemplate = maskset._buffer;
  1788. bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "";
  1789. return result !== bufferTemplate ? result : "";
  1790. }
  1791. } else return valhookGet(elem);
  1792. },
  1793. set: function(elem, value) {
  1794. var $elem = $(elem),
  1795. result;
  1796. result = valhookSet(elem, value);
  1797. if (elem.inputmask) {
  1798. $elem.trigger("setvalue.inputmask");
  1799. }
  1800. return result;
  1801. },
  1802. inputmaskpatch: true
  1803. };
  1804. }
  1805. }
  1806. function getter() {
  1807. if (this.inputmask) {
  1808. return this.inputmask.opts.autoUnmask ?
  1809. this.inputmask.unmaskedvalue() :
  1810. (valueGet.call(this) !== getBufferTemplate().join("") ?
  1811. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  1812. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  1813. valueGet.call(this)) :
  1814. "");
  1815. } else return valueGet.call(this);
  1816. }
  1817. function setter(value) {
  1818. valueSet.call(this, value);
  1819. if (this.inputmask) {
  1820. $(this).trigger("setvalue.inputmask");
  1821. }
  1822. }
  1823. function installNativeValueSetFallback(npt) {
  1824. $(npt).on("mouseenter.inputmask", wrapEventRuler(function(event) {
  1825. var $input = $(this),
  1826. input = this,
  1827. value = input.inputmask._valueGet();
  1828. if (value !== "" && value !== getBuffer().join("")) {
  1829. $input.trigger("setvalue.inputmask");
  1830. }
  1831. }));
  1832. }
  1833. if (!npt.inputmask.__valueGet) {
  1834. if (Object.getOwnPropertyDescriptor && npt.value === undefined) { // && npt.isContentEditable) {
  1835. valueGet = function() {
  1836. return this.textContent;
  1837. };
  1838. valueSet = function(value) {
  1839. this.textContent = value;
  1840. };
  1841. Object.defineProperty(npt, "value", {
  1842. get: getter,
  1843. set: setter
  1844. });
  1845. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1846. valueGet = npt.__lookupGetter__("value");
  1847. valueSet = npt.__lookupSetter__("value");
  1848. npt.__defineGetter__("value", getter);
  1849. npt.__defineSetter__("value", setter);
  1850. } else { //jquery.val
  1851. valueGet = function() {
  1852. return npt.value;
  1853. };
  1854. valueSet = function(value) {
  1855. npt.value = value;
  1856. };
  1857. patchValhook(npt.type);
  1858. installNativeValueSetFallback(npt);
  1859. }
  1860. npt.inputmask.__valueGet = valueGet; //store native property getter
  1861. npt.inputmask._valueGet = function(overruleRTL) {
  1862. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  1863. };
  1864. npt.inputmask.__valueSet = valueSet; //store native property setter
  1865. npt.inputmask._valueSet = function(value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  1866. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  1867. };
  1868. }
  1869. }
  1870. function handleRemove(input, k, pos, strict) {
  1871. function generalize() {
  1872. if (opts.keepStatic) {
  1873. resetMaskSet(true);
  1874. var validInputs = [],
  1875. lastAlt, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
  1876. //find last alternation
  1877. for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) {
  1878. var validPos = getMaskSet().validPositions[lastAlt];
  1879. if (validPos) {
  1880. if (validPos.match.fn != null) {
  1881. validInputs.push(validPos.input);
  1882. }
  1883. delete getMaskSet().validPositions[lastAlt];
  1884. if (validPos.alternation !== undefined && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation]) {
  1885. break;
  1886. }
  1887. }
  1888. }
  1889. if (lastAlt > -1) {
  1890. while (validInputs.length > 0) {
  1891. getMaskSet().p = seekNext(getLastValidPosition());
  1892. var keypress = $.Event("keypress");
  1893. keypress.which = validInputs.pop().charCodeAt(0);
  1894. keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1895. }
  1896. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1897. }
  1898. }
  1899. if (opts.numericInput || isRTL) {
  1900. if (k === Inputmask.keyCode.BACKSPACE) {
  1901. k = Inputmask.keyCode.DELETE;
  1902. } else if (k === Inputmask.keyCode.DELETE) {
  1903. k = Inputmask.keyCode.BACKSPACE;
  1904. }
  1905. if (isRTL) {
  1906. var pend = pos.end;
  1907. pos.end = pos.begin;
  1908. pos.begin = pend;
  1909. }
  1910. }
  1911. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1912. pos.begin = seekPrevious(pos.begin);
  1913. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1914. pos.begin--;
  1915. }
  1916. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1917. pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1;
  1918. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1919. pos.end++;
  1920. }
  1921. }
  1922. stripValidPositions(pos.begin, pos.end, false, strict);
  1923. if (strict !== true) {
  1924. generalize(); //revert the alternation
  1925. }
  1926. var lvp = getLastValidPosition(pos.begin);
  1927. if (lvp < pos.begin) {
  1928. if (lvp === -1) resetMaskSet();
  1929. getMaskSet().p = seekNext(lvp);
  1930. } else if (strict !== true) {
  1931. getMaskSet().p = pos.begin;
  1932. }
  1933. }
  1934. function keydownEvent(e) {
  1935. var input = this,
  1936. $input = $(input),
  1937. k = e.keyCode,
  1938. pos = caret(input);
  1939. //backspace, delete, and escape get special treatment
  1940. if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || (iphone && k === 127) || (e.ctrlKey && k === 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1941. e.preventDefault(); //stop default action but allow propagation
  1942. if (k === 88) undoValue = getBuffer().join("");
  1943. handleRemove(input, k, pos);
  1944. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  1945. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  1946. $input.trigger("cleared");
  1947. } else if (isComplete(getBuffer()) === true) {
  1948. $input.trigger("complete");
  1949. }
  1950. if (opts.showTooltip) { //update tooltip
  1951. input.title = opts.tooltip || getMaskSet().mask;
  1952. }
  1953. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1954. setTimeout(function() {
  1955. var caretPos = seekNext(getLastValidPosition());
  1956. if (!opts.insertMode && caretPos === getMaskLength() && !e.shiftKey) caretPos--;
  1957. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1958. }, 0);
  1959. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  1960. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1961. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  1962. checkVal(input, true, false, undoValue.split(""));
  1963. $input.trigger("click");
  1964. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1965. opts.insertMode = !opts.insertMode;
  1966. caret(input, !opts.insertMode && pos.begin === getMaskLength() ? pos.begin - 1 : pos.begin);
  1967. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  1968. if (e.shiftKey === true) {
  1969. if (getTest(pos.begin).fn === null) {
  1970. pos.begin = seekNext(pos.begin);
  1971. }
  1972. pos.end = seekPrevious(pos.begin, true);
  1973. pos.begin = seekPrevious(pos.end, true);
  1974. } else {
  1975. pos.begin = seekNext(pos.begin, true);
  1976. pos.end = seekNext(pos.begin, true);
  1977. if (pos.end < getMaskLength()) pos.end--;
  1978. }
  1979. if (pos.begin < getMaskLength()) {
  1980. e.preventDefault();
  1981. caret(input, pos.begin, pos.end);
  1982. }
  1983. } else if (opts.insertMode === false && !e.shiftKey) {
  1984. if (k === Inputmask.keyCode.RIGHT) {
  1985. setTimeout(function() {
  1986. var caretPos = caret(input);
  1987. caret(input, caretPos.begin);
  1988. }, 0);
  1989. } else if (k === Inputmask.keyCode.LEFT) {
  1990. setTimeout(function() {
  1991. var caretPos = caret(input);
  1992. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1993. }, 0);
  1994. }
  1995. }
  1996. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts); //this is needed in onKeyDown
  1997. ignorable = $.inArray(k, opts.ignorables) !== -1;
  1998. }
  1999. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  2000. var input = this,
  2001. $input = $(input),
  2002. k = e.which || e.charCode || e.keyCode;
  2003. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2004. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2005. undoValue = getBuffer().join("");
  2006. e.preventDefault();
  2007. setTimeout(function() {
  2008. $input.trigger("change");
  2009. }, 0);
  2010. }
  2011. return true;
  2012. } else {
  2013. if (k) {
  2014. //special treat the decimal separator
  2015. if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
  2016. var pos = checkval ? {
  2017. begin: ndx,
  2018. end: ndx
  2019. } : caret(input),
  2020. forwardPosition, c = String.fromCharCode(k);
  2021. //should we clear a possible selection??
  2022. var isSlctn = isSelection(pos.begin, pos.end);
  2023. if (isSlctn) {
  2024. getMaskSet().undoPositions = $.extend(true, {}, getMaskSet().validPositions); //init undobuffer for recovery when not valid
  2025. handleRemove(input, Inputmask.keyCode.DELETE, pos, true);
  2026. pos.begin = getMaskSet().p;
  2027. if (!opts.insertMode) { //preserve some space
  2028. opts.insertMode = !opts.insertMode;
  2029. setValidPosition(pos.begin, strict);
  2030. opts.insertMode = !opts.insertMode;
  2031. }
  2032. isSlctn = !opts.multi;
  2033. }
  2034. getMaskSet().writeOutBuffer = true;
  2035. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  2036. var valResult = isValid(p, c, strict);
  2037. if (valResult !== false) {
  2038. if (valResult !== true) {
  2039. p = valResult.pos !== undefined ? valResult.pos : p; //set new position from isValid
  2040. c = valResult.c !== undefined ? valResult.c : c; //set new char from isValid
  2041. }
  2042. resetMaskSet(true);
  2043. if (valResult.caret !== undefined) {
  2044. forwardPosition = valResult.caret;
  2045. } else {
  2046. var vps = getMaskSet().validPositions;
  2047. if (!opts.keepStatic && (vps[p + 1] !== undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation !== undefined)) {
  2048. forwardPosition = p + 1;
  2049. } else forwardPosition = seekNext(p);
  2050. }
  2051. getMaskSet().p = forwardPosition; //needed for checkval
  2052. }
  2053. if (writeOut !== false) {
  2054. var self = this;
  2055. setTimeout(function() {
  2056. opts.onKeyValidation.call(self, k, valResult, opts);
  2057. }, 0);
  2058. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2059. var buffer = getBuffer();
  2060. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2061. if (checkval !== true) {
  2062. setTimeout(function() { //timeout needed for IE
  2063. if (isComplete(buffer) === true) $input.trigger("complete");
  2064. }, 0);
  2065. }
  2066. } else if (isSlctn) {
  2067. getMaskSet().buffer = undefined;
  2068. getMaskSet().validPositions = getMaskSet().undoPositions;
  2069. }
  2070. } else if (isSlctn) {
  2071. getMaskSet().buffer = undefined;
  2072. getMaskSet().validPositions = getMaskSet().undoPositions;
  2073. }
  2074. if (opts.showTooltip) { //update tooltip
  2075. input.title = opts.tooltip || getMaskSet().mask;
  2076. }
  2077. if (checkval && $.isFunction(opts.onBeforeWrite)) {
  2078. var result = opts.onBeforeWrite(e, getBuffer(), forwardPosition, opts);
  2079. if (result && result.refreshFromBuffer) {
  2080. var refresh = result.refreshFromBuffer;
  2081. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  2082. resetMaskSet(true);
  2083. if (result.caret) {
  2084. getMaskSet().p = result.caret;
  2085. }
  2086. }
  2087. }
  2088. e.preventDefault();
  2089. if (checkval) {
  2090. return valResult;
  2091. }
  2092. }
  2093. }
  2094. }
  2095. function pasteEvent(e) {
  2096. var input = this,
  2097. ev = e.originalEvent || e,
  2098. $input = $(input),
  2099. inputValue = input.inputmask._valueGet(true),
  2100. caretPos = caret(input);
  2101. //paste event for IE8 and lower I guess ;-)
  2102. if (e.type === "propertychange" && input.inputmask._valueGet().length <= getMaskLength()) {
  2103. return true;
  2104. } else if (e.type === "paste") {
  2105. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2106. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2107. if (valueBeforeCaret === getBufferTemplate().slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2108. if (valueAfterCaret === getBufferTemplate().slice(caretPos.end).join("")) valueAfterCaret = "";
  2109. if (window.clipboardData && window.clipboardData.getData) { // IE
  2110. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2111. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2112. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2113. }
  2114. }
  2115. var pasteValue = inputValue;
  2116. if ($.isFunction(opts.onBeforePaste)) {
  2117. pasteValue = opts.onBeforePaste.call(input, inputValue, opts);
  2118. if (pasteValue === false) {
  2119. e.preventDefault();
  2120. return false;
  2121. }
  2122. if (!pasteValue) {
  2123. pasteValue = inputValue;
  2124. }
  2125. }
  2126. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2127. writeBuffer(input, getBuffer(), undefined, e, true);
  2128. $input.trigger("click");
  2129. if (isComplete(getBuffer()) === true) {
  2130. $input.trigger("complete");
  2131. }
  2132. return false;
  2133. }
  2134. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  2135. var input = this;
  2136. checkVal(input, true, false, input.inputmask._valueGet().split(""));
  2137. if (isComplete(getBuffer()) === true) {
  2138. $(input).trigger("complete");
  2139. }
  2140. e.preventDefault();
  2141. }
  2142. function mobileInputEvent(e) {
  2143. var input = this;
  2144. //backspace in chrome32 only fires input event - detect & treat
  2145. var caretPos = caret(input),
  2146. currentValue = input._valueGet();
  2147. currentValue = currentValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2148. //correct caretposition for chrome
  2149. if (caretPos.begin > currentValue.length) {
  2150. caret(input, currentValue.length);
  2151. caretPos = caret(input);
  2152. }
  2153. if ((getBuffer().length - currentValue.length) === 1 && currentValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && currentValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2154. e.keyCode = opts.keyCode.BACKSPACE;
  2155. keydownEvent.call(input, e);
  2156. } else {
  2157. inputFallBackEvent.call(this, e);
  2158. }
  2159. e.preventDefault();
  2160. }
  2161. function compositionStartEvent(e) {
  2162. var ev = e.originalEvent || e;
  2163. undoValue = getBuffer().join("");
  2164. if (compositionData === "" || ev.data.indexOf(compositionData) !== 0) {
  2165. // compositionCaretPos = caret(input);
  2166. }
  2167. }
  2168. function compositionUpdateEvent(e) {
  2169. var input = this,
  2170. ev = e.originalEvent || e;
  2171. if (ev.data.indexOf(compositionData) === 0) {
  2172. resetMaskSet();
  2173. getMaskSet().p = seekNext(-1); //needs check
  2174. skipInputEvent = true;
  2175. }
  2176. var newData = ev.data;
  2177. for (var i = 0; i < newData.length; i++) {
  2178. var keypress = $.Event("keypress");
  2179. keypress.which = newData.charCodeAt(i);
  2180. skipKeyPressEvent = false;
  2181. ignorable = false;
  2182. keypressEvent.call(input, keypress, true, false, false, getMaskSet().p); //needs check
  2183. }
  2184. setTimeout(function() {
  2185. var forwardPosition = getMaskSet().p;
  2186. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  2187. }, 0);
  2188. compositionData = ev.data;
  2189. }
  2190. function compositionEndEvent(e) {
  2191. //pickup by inputfallback
  2192. }
  2193. function setValueEvent(e) {
  2194. var input = this,
  2195. value = input.inputmask._valueGet();
  2196. checkVal(input, true, false, ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(input, value, opts) || value) : value).split(""));
  2197. undoValue = getBuffer().join("");
  2198. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2199. input.inputmask._valueSet("");
  2200. }
  2201. }
  2202. function focusEvent(e) {
  2203. var input = this,
  2204. nptValue = input.inputmask._valueGet();
  2205. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2206. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2207. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2208. }
  2209. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2210. caret(input, seekNext(getLastValidPosition()));
  2211. }
  2212. if (opts.positionCaretOnTab === true) {
  2213. setTimeout(function() {
  2214. caret(input, seekNext(getLastValidPosition()));
  2215. }, 0);
  2216. }
  2217. undoValue = getBuffer().join("");
  2218. }
  2219. function mouseleaveEvent(e) {
  2220. var input = this;
  2221. mouseEnter = false;
  2222. if (opts.clearMaskOnLostFocus) {
  2223. var buffer = getBuffer().slice(),
  2224. nptValue = input.inputmask._valueGet();
  2225. if (document.activeElement !== input && nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2226. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2227. buffer = [];
  2228. } else { //clearout optional tail of the mask
  2229. clearOptionalTail(buffer);
  2230. }
  2231. writeBuffer(input, buffer);
  2232. }
  2233. }
  2234. }
  2235. function clickEvent(e) {
  2236. function doRadixFocus(clickPos) {
  2237. if (opts.radixFocus && opts.radixPoint !== "") {
  2238. var vps = getMaskSet().validPositions;
  2239. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2240. if (clickPos < seekNext(-1)) return true;
  2241. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2242. if (radixPos !== -1) {
  2243. for (var vp in vps) {
  2244. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2245. return false;
  2246. }
  2247. }
  2248. return true;
  2249. }
  2250. }
  2251. }
  2252. return false;
  2253. }
  2254. var input = this;
  2255. if (document.activeElement === input) {
  2256. var selectedCaret = caret(input);
  2257. if (selectedCaret.begin === selectedCaret.end) {
  2258. if (doRadixFocus(selectedCaret.begin)) {
  2259. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  2260. } else {
  2261. var clickPosition = selectedCaret.begin,
  2262. lvclickPosition = getLastValidPosition(clickPosition),
  2263. lastPosition = seekNext(lvclickPosition);
  2264. if (clickPosition < lastPosition) {
  2265. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2266. } else {
  2267. caret(input, opts.numericInput ? 0 : lastPosition);
  2268. }
  2269. }
  2270. }
  2271. }
  2272. }
  2273. function dblclickEvent(e) {
  2274. var input = this;
  2275. setTimeout(function() {
  2276. caret(input, 0, seekNext(getLastValidPosition()));
  2277. }, 0);
  2278. }
  2279. function cutEvent(e) {
  2280. var input = this,
  2281. $input = $(input),
  2282. pos = caret(input),
  2283. ev = e.originalEvent || e;
  2284. //correct clipboardData
  2285. var clipboardData = window.clipboardData || ev.clipboardData,
  2286. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2287. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2288. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2289. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2290. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2291. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2292. $input.trigger("cleared");
  2293. }
  2294. if (opts.showTooltip) { //update tooltip
  2295. input.title = opts.tooltip || getMaskSet().mask;
  2296. }
  2297. }
  2298. function blurEvent(e) {
  2299. var $input = $(this),
  2300. input = this;
  2301. if (input.inputmask) {
  2302. var nptValue = input.inputmask._valueGet(),
  2303. buffer = getBuffer().slice();
  2304. if (undoValue !== buffer.join("")) {
  2305. setTimeout(function() { //change event should be triggered after the other buffer manipulations on blur
  2306. $input.trigger("change");
  2307. undoValue = buffer.join("");
  2308. }, 0);
  2309. }
  2310. if (nptValue !== "") {
  2311. if (opts.clearMaskOnLostFocus) {
  2312. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2313. buffer = [];
  2314. } else { //clearout optional tail of the mask
  2315. clearOptionalTail(buffer);
  2316. }
  2317. }
  2318. if (isComplete(buffer) === false) {
  2319. setTimeout(function() {
  2320. $input.trigger("incomplete");
  2321. }, 0);
  2322. if (opts.clearIncomplete) {
  2323. resetMaskSet();
  2324. if (opts.clearMaskOnLostFocus) {
  2325. buffer = [];
  2326. } else {
  2327. buffer = getBufferTemplate().slice();
  2328. }
  2329. }
  2330. }
  2331. writeBuffer(input, buffer, undefined, e);
  2332. }
  2333. }
  2334. }
  2335. function mouseenterEvent(e) {
  2336. var input = this;
  2337. mouseEnter = true;
  2338. if (document.activeElement !== input && opts.showMaskOnHover) {
  2339. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2340. writeBuffer(input, getBuffer());
  2341. }
  2342. }
  2343. }
  2344. function submitEvent(e) { //trigger change on submit if any
  2345. if (undoValue !== getBuffer().join("")) {
  2346. $el.trigger("change");
  2347. }
  2348. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2349. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2350. }
  2351. if (opts.removeMaskOnSubmit) {
  2352. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2353. setTimeout(function() {
  2354. writeBuffer(el, getBuffer());
  2355. }, 0);
  2356. }
  2357. }
  2358. function resetEvent(e) {
  2359. setTimeout(function() {
  2360. $el.trigger("setvalue.inputmask");
  2361. }, 0);
  2362. }
  2363. function mask(elem) {
  2364. el = elem;
  2365. $el = $(el);
  2366. //show tooltip
  2367. if (opts.showTooltip) {
  2368. el.title = opts.tooltip || getMaskSet().mask;
  2369. }
  2370. if (el.dir === "rtl" || opts.rightAlign) {
  2371. el.style.textAlign = "right";
  2372. }
  2373. if (el.dir === "rtl" || opts.numericInput) {
  2374. el.dir = "ltr";
  2375. el.removeAttribute("dir");
  2376. el.inputmask.isRTL = true;
  2377. isRTL = true;
  2378. }
  2379. //unbind all events - to make sure that no other mask will interfere when re-masking
  2380. $el.off(".inputmask");
  2381. patchValueProperty(el);
  2382. if ((el.tagName === "INPUT" && isInputTypeSupported(el.getAttribute("type"))) || el.isContentEditable) {
  2383. //bind events
  2384. $(el.form).on("submit.inputmask", submitEvent).on("reset.inputmask", resetEvent);
  2385. $el.on("mouseenter.inputmask", wrapEventRuler(mouseenterEvent))
  2386. .on("blur.inputmask", wrapEventRuler(blurEvent))
  2387. .on("focus.inputmask", wrapEventRuler(focusEvent))
  2388. .on("mouseleave.inputmask", wrapEventRuler(mouseleaveEvent))
  2389. .on("click.inputmask", wrapEventRuler(clickEvent))
  2390. .on("dblclick.inputmask", wrapEventRuler(dblclickEvent))
  2391. .on(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", wrapEventRuler(pasteEvent))
  2392. .on("cut.inputmask", wrapEventRuler(cutEvent))
  2393. .on("complete.inputmask", wrapEventRuler(opts.oncomplete))
  2394. .on("incomplete.inputmask", wrapEventRuler(opts.onincomplete))
  2395. .on("cleared.inputmask", wrapEventRuler(opts.oncleared))
  2396. .on("keydown.inputmask", wrapEventRuler(keydownEvent))
  2397. .on("keypress.inputmask", wrapEventRuler(keypressEvent));
  2398. if (!androidfirefox) {
  2399. $el.on("compositionstart.inputmask", wrapEventRuler(compositionStartEvent))
  2400. .on("compositionupdate.inputmask", wrapEventRuler(compositionUpdateEvent))
  2401. .on("compositionend.inputmask", wrapEventRuler(compositionEndEvent));
  2402. }
  2403. if (PasteEventType === "paste") {
  2404. $el.on("input.inputmask", wrapEventRuler(inputFallBackEvent));
  2405. }
  2406. if (android || androidfirefox || androidchrome || kindle) {
  2407. $el.off("input.inputmask");
  2408. $el.on("input.inputmask", wrapEventRuler(mobileInputEvent));
  2409. }
  2410. }
  2411. $el.on("setvalue.inputmask", wrapEventRuler(setValueEvent));
  2412. //apply mask
  2413. if (el.inputmask._valueGet() !== "" || opts.clearMaskOnLostFocus === false) {
  2414. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2415. checkVal(el, true, false, initialValue.split(""));
  2416. var buffer = getBuffer().slice();
  2417. undoValue = buffer.join("");
  2418. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2419. if (isComplete(buffer) === false) {
  2420. if (opts.clearIncomplete) {
  2421. resetMaskSet();
  2422. }
  2423. }
  2424. if (opts.clearMaskOnLostFocus) {
  2425. if (buffer.join("") === getBufferTemplate().join("")) {
  2426. buffer = [];
  2427. } else {
  2428. clearOptionalTail(buffer);
  2429. }
  2430. }
  2431. writeBuffer(el, buffer);
  2432. if (document.activeElement === el) { //position the caret when in focus
  2433. caret(el, seekNext(getLastValidPosition()));
  2434. }
  2435. }
  2436. }
  2437. //action object
  2438. var valueBuffer;
  2439. if (actionObj !== undefined) {
  2440. switch (actionObj.action) {
  2441. case "isComplete":
  2442. el = actionObj.el;
  2443. return isComplete(getBuffer());
  2444. case "unmaskedvalue":
  2445. el = actionObj.el;
  2446. if (el !== undefined && el.inputmask !== undefined) {
  2447. maskset = el.inputmask.maskset;
  2448. opts = el.inputmask.opts;
  2449. isRTL = el.inputmask.isRTL;
  2450. } else {
  2451. valueBuffer = actionObj.value;
  2452. if (opts.numericInput) {
  2453. isRTL = true;
  2454. }
  2455. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2456. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2457. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2458. }
  2459. return unmaskedvalue(el);
  2460. case "mask":
  2461. el = actionObj.el;
  2462. maskset = el.inputmask.maskset;
  2463. opts = el.inputmask.opts;
  2464. isRTL = el.inputmask.isRTL;
  2465. undoValue = getBuffer().join("");
  2466. mask(el);
  2467. break;
  2468. case "format":
  2469. if (opts.numericInput) {
  2470. isRTL = true;
  2471. }
  2472. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2473. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2474. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2475. if (actionObj.metadata) {
  2476. return {
  2477. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2478. metadata: maskScope({
  2479. "action": "getmetadata"
  2480. }, maskset, opts)
  2481. };
  2482. }
  2483. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2484. case "isValid":
  2485. if (opts.numericInput) {
  2486. isRTL = true;
  2487. }
  2488. valueBuffer = actionObj.value.split("");
  2489. checkVal(undefined, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2490. var buffer = getBuffer();
  2491. var rl = determineLastRequiredPosition(),
  2492. lmib = buffer.length - 1;
  2493. for (; lmib > rl; lmib--) {
  2494. if (isMask(lmib)) break;
  2495. }
  2496. buffer.splice(rl, lmib + 1 - rl);
  2497. return isComplete(buffer) && actionObj.value === buffer.join("");
  2498. case "getemptymask":
  2499. return getBufferTemplate();
  2500. case "remove":
  2501. el = actionObj.el;
  2502. $el = $(el);
  2503. maskset = el.inputmask.maskset;
  2504. opts = el.inputmask.opts;
  2505. //writeout the unmaskedvalue
  2506. el.inputmask._valueSet(unmaskedvalue(el));
  2507. //unbind all events
  2508. $el.off(".inputmask");
  2509. //restore the value property
  2510. var valueProperty;
  2511. if (Object.getOwnPropertyDescriptor) {
  2512. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  2513. }
  2514. if (valueProperty && valueProperty.get) {
  2515. if (el.inputmask.__valueGet) {
  2516. Object.defineProperty(el, "value", {
  2517. get: el.inputmask.__valueGet,
  2518. set: el.inputmask.__valueSet
  2519. });
  2520. }
  2521. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2522. if (el.inputmask.__valueGet) {
  2523. el.__defineGetter__("value", el.inputmask.__valueGet);
  2524. el.__defineSetter__("value", el.inputmask.__valueSet);
  2525. }
  2526. }
  2527. //clear data
  2528. el.inputmask = undefined;
  2529. break;
  2530. case "getmetadata":
  2531. if ($.isArray(maskset.metadata)) {
  2532. //find last alternation
  2533. var alternation, lvp = getLastValidPosition();
  2534. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  2535. if (getMaskSet().validPositions[firstAlt] && getMaskSet().validPositions[firstAlt].alternation !== undefined) {
  2536. alternation = getMaskSet().validPositions[firstAlt].alternation;
  2537. break;
  2538. }
  2539. }
  2540. if (alternation !== undefined) {
  2541. return maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]];
  2542. } else return maskset.metadata[0];
  2543. }
  2544. return maskset.metadata;
  2545. }
  2546. }
  2547. }
  2548. //make inputmask available
  2549. window.Inputmask = Inputmask;
  2550. return Inputmask;
  2551. }));