inputmask.js 101 KB

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